From 31ee540a0aebdfb2bda4557547ece82497bf430f Mon Sep 17 00:00:00 2001 From: "github-action[bot]" Date: Sun, 7 Sep 2025 20:32:43 +0200 Subject: [PATCH] Update On Sun Sep 7 20:32:43 CEST 2025 --- .github/update.log | 1 + bbdown/BBDown/BBDownUtil.cs | 15 +- clash-meta/config/config.go | 2 + clash-meta/docs/config.yaml | 2 + clash-meta/listener/config/tun.go | 4 + clash-meta/listener/inbound/tun.go | 2 + clash-meta/listener/sing_tun/dns.go | 3 +- clash-meta/listener/sing_tun/prepare.go | 2 +- clash-meta/listener/sing_tun/server.go | 5 +- clash-nyanpasu/backend/Cargo.lock | 6 +- .../frontend/interface/package.json | 2 +- clash-nyanpasu/frontend/nyanpasu/package.json | 6 +- clash-nyanpasu/package.json | 4 +- clash-nyanpasu/pnpm-lock.yaml | 138 +- ...k-for-another-multigig-RollBall-tran.patch | 30 + ...dd-quirk-for-FlyPro-10Gbase-T-module.patch | 28 + ...dd-quirk-for-FlyPro-10Gbase-T-module.patch | 28 + mieru/pkg/protocol/mux.go | 21 +- mieru/pkg/protocol/underlay_base.go | 6 +- mieru/pkg/protocol/underlay_packet.go | 27 +- mieru/pkg/protocol/underlay_stream.go | 29 +- mihomo/config/config.go | 2 + mihomo/docs/config.yaml | 2 + mihomo/listener/config/tun.go | 4 + mihomo/listener/inbound/tun.go | 2 + mihomo/listener/sing_tun/dns.go | 3 +- mihomo/listener/sing_tun/prepare.go | 2 +- mihomo/listener/sing_tun/server.go | 5 +- nekobox-android/.github/workflows/preview.yml | 2 +- nekobox-android/.github/workflows/release.yml | 2 +- .../java/com/wireguard/crypto/Curve25519.java | 497 -- .../java/com/wireguard/crypto/Ed25519.java | 2508 ---------- .../main/java/com/wireguard/crypto/Key.java | 288 -- .../wireguard/crypto/KeyFormatException.java | 34 - .../java/com/wireguard/crypto/KeyPair.java | 51 - .../nekohasekai/sagernet/ui/LogcatFragment.kt | 6 - .../sagernet/ui/NetworkFragment.kt | 63 +- .../sagernet/ui/profile/ConfigEditActivity.kt | 12 +- .../nekohasekai/sagernet/utils/Cloudflare.kt | 74 - .../sagernet/utils/cf/DeviceResponse.kt | 114 - .../sagernet/utils/cf/RegisterRequest.kt | 33 - .../sagernet/utils/cf/UpdateDeviceRequest.kt | 12 - .../moe/matsuri/nb4a/net/LocalResolverImpl.kt | 198 +- .../src/main/res/layout/layout_network.xml | 57 - nekobox-android/libcore/box_include.go | 5 +- nekobox-android/libcore/dns_android.go | 114 + nekobox-android/libcore/dns_box.go | 148 +- nekobox-android/libcore/nb4a.go | 3 +- nekobox-android/nb4a.properties | 2 +- shadowsocks-rust/Cargo.lock | 102 +- shadowsocks-rust/Cargo.toml | 2 +- sing-box/.github/workflows/build.yml | 4 +- sing-box/Dockerfile | 2 +- sing-box/cmd/internal/build_libbox/main.go | 8 +- sing-box/common/badtls/raw_conn.go | 169 + sing-box/common/badtls/raw_half_conn.go | 121 + sing-box/common/badtls/read_wait.go | 122 +- sing-box/common/badtls/read_wait_stub.go | 2 +- sing-box/common/badtls/read_wait_utls.go | 36 - sing-box/common/badtls/registry.go | 62 + sing-box/common/badtls/registry_utls.go | 56 + sing-box/common/ktls/ktls.go | 84 + sing-box/common/ktls/ktls_alert.go | 80 + .../common/ktls/ktls_cipher_suites_linux.go | 326 ++ sing-box/common/ktls/ktls_close.go | 67 + sing-box/common/ktls/ktls_const.go | 24 + .../common/ktls/ktls_handshake_messages.go | 238 + sing-box/common/ktls/ktls_key_update.go | 173 + sing-box/common/ktls/ktls_linux.go | 311 ++ sing-box/common/ktls/ktls_prf.go | 24 + sing-box/common/ktls/ktls_read.go | 292 ++ sing-box/common/ktls/ktls_read_wait.go | 41 + sing-box/common/ktls/ktls_stub.go | 13 + sing-box/common/ktls/ktls_write.go | 154 + sing-box/common/tls/client.go | 8 + sing-box/common/tls/config.go | 6 + sing-box/common/tls/server.go | 8 + sing-box/common/tls/std_client.go | 29 +- sing-box/common/tls/std_server.go | 33 +- sing-box/common/tls/utls_client.go | 19 +- sing-box/go.mod | 3 +- sing-box/go.sum | 6 +- sing-box/option/tls.go | 4 + sing-box/release/local/debug.sh | 2 +- sing-box/release/local/install.sh | 2 +- sing-box/release/local/reinstall.sh | 2 +- sing-box/route/conn.go | 36 +- sing-box/transport/trojan/protocol.go | 8 + v2ray-core/.github/workflows/release.yml | 2 +- v2ray-core/.github/workflows/stale.yml | 2 +- v2rayn/package-debian.sh | 1 + .../v2rayN/ServiceLib/Resx/ResUI.Designer.cs | 9 + .../v2rayN/ServiceLib/Resx/ResUI.fa-Ir.resx | 3 + v2rayn/v2rayN/ServiceLib/Resx/ResUI.hu.resx | 3 + v2rayn/v2rayN/ServiceLib/Resx/ResUI.resx | 3 + v2rayn/v2rayN/ServiceLib/Resx/ResUI.ru.resx | 3 + .../v2rayN/ServiceLib/Resx/ResUI.zh-Hans.resx | 3 + .../v2rayN/ServiceLib/Resx/ResUI.zh-Hant.resx | 3 + .../ViewModels/ProfilesSelectViewModel.cs | 359 ++ .../ViewModels/ProfilesViewModel.cs | 25 - .../Views/ProfilesSelectWindow.axaml | 136 + .../Views/ProfilesSelectWindow.axaml.cs | 200 + .../Views/RoutingRuleDetailsWindow.axaml | 15 +- .../Views/RoutingRuleDetailsWindow.axaml.cs | 16 + .../v2rayN.Desktop/Views/SubEditWindow.axaml | 12 + .../Views/SubEditWindow.axaml.cs | 31 + .../v2rayN/Views/ProfilesSelectWindow.xaml | 156 + .../v2rayN/Views/ProfilesSelectWindow.xaml.cs | 194 + .../v2rayN/v2rayN/Views/ProfilesView.xaml.cs | 4 +- .../Views/RoutingRuleDetailsWindow.xaml | 16 +- .../Views/RoutingRuleDetailsWindow.xaml.cs | 15 + v2rayn/v2rayN/v2rayN/Views/SubEditWindow.xaml | 16 + .../v2rayN/v2rayN/Views/SubEditWindow.xaml.cs | 28 + xray-core/app/reverse/portal.go | 14 + xray-core/common/mux/client.go | 4 + xray-core/main/commands/all/tls/ping.go | 2 +- yt-dlp/.github/actionlint.yml | 28 + yt-dlp/.github/workflows/build.yml | 33 +- yt-dlp/.github/workflows/cache-warmer.yml | 1 + yt-dlp/.github/workflows/release.yml | 13 +- yt-dlp/.github/workflows/test-workflows.yml | 46 + yt-dlp/README.md | 11 + yt-dlp/THIRD_PARTY_LICENSES.txt | 4433 +++++++++++++++++ yt-dlp/bundle/pyinstaller.py | 1 - .../generate_third_party_licenses.py | 316 ++ yt-dlp/pyproject.toml | 8 +- yt-dlp/test/test_compat.py | 42 +- yt-dlp/test/test_utils.py | 21 + yt-dlp/yt_dlp/YoutubeDL.py | 6 +- yt-dlp/yt_dlp/compat/__init__.py | 8 + yt-dlp/yt_dlp/utils/_utils.py | 15 +- 131 files changed, 9201 insertions(+), 4339 deletions(-) create mode 100644 lede/target/linux/generic/backport-6.6/786-v6.10-net-sfp-add-quirk-for-another-multigig-RollBall-tran.patch create mode 100644 lede/target/linux/generic/pending-6.12/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch create mode 100644 lede/target/linux/generic/pending-6.6/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch delete mode 100644 nekobox-android/app/src/main/java/com/wireguard/crypto/Curve25519.java delete mode 100644 nekobox-android/app/src/main/java/com/wireguard/crypto/Ed25519.java delete mode 100644 nekobox-android/app/src/main/java/com/wireguard/crypto/Key.java delete mode 100644 nekobox-android/app/src/main/java/com/wireguard/crypto/KeyFormatException.java delete mode 100644 nekobox-android/app/src/main/java/com/wireguard/crypto/KeyPair.java delete mode 100644 nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt delete mode 100644 nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt delete mode 100644 nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt delete mode 100644 nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt create mode 100644 nekobox-android/libcore/dns_android.go create mode 100644 sing-box/common/badtls/raw_conn.go create mode 100644 sing-box/common/badtls/raw_half_conn.go delete mode 100644 sing-box/common/badtls/read_wait_utls.go create mode 100644 sing-box/common/badtls/registry.go create mode 100644 sing-box/common/badtls/registry_utls.go create mode 100644 sing-box/common/ktls/ktls.go create mode 100644 sing-box/common/ktls/ktls_alert.go create mode 100644 sing-box/common/ktls/ktls_cipher_suites_linux.go create mode 100644 sing-box/common/ktls/ktls_close.go create mode 100644 sing-box/common/ktls/ktls_const.go create mode 100644 sing-box/common/ktls/ktls_handshake_messages.go create mode 100644 sing-box/common/ktls/ktls_key_update.go create mode 100644 sing-box/common/ktls/ktls_linux.go create mode 100644 sing-box/common/ktls/ktls_prf.go create mode 100644 sing-box/common/ktls/ktls_read.go create mode 100644 sing-box/common/ktls/ktls_read_wait.go create mode 100644 sing-box/common/ktls/ktls_stub.go create mode 100644 sing-box/common/ktls/ktls_write.go create mode 100644 v2rayn/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs create mode 100644 v2rayn/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml create mode 100644 v2rayn/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs create mode 100644 v2rayn/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml create mode 100644 v2rayn/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs create mode 100644 yt-dlp/.github/actionlint.yml create mode 100644 yt-dlp/.github/workflows/test-workflows.yml create mode 100644 yt-dlp/THIRD_PARTY_LICENSES.txt create mode 100644 yt-dlp/devscripts/generate_third_party_licenses.py diff --git a/.github/update.log b/.github/update.log index fc938309b8..0e05e4760a 100644 --- a/.github/update.log +++ b/.github/update.log @@ -1113,3 +1113,4 @@ Update On Wed Sep 3 20:39:00 CEST 2025 Update On Thu Sep 4 20:39:26 CEST 2025 Update On Fri Sep 5 20:37:42 CEST 2025 Update On Sat Sep 6 20:35:46 CEST 2025 +Update On Sun Sep 7 20:32:35 CEST 2025 diff --git a/bbdown/BBDown/BBDownUtil.cs b/bbdown/BBDown/BBDownUtil.cs index 1568f39010..3cf1066637 100644 --- a/bbdown/BBDown/BBDownUtil.cs +++ b/bbdown/BBDown/BBDownUtil.cs @@ -195,10 +195,17 @@ static partial class BBDownUtil public static string FormatTime(int time, bool absolute = false) { - TimeSpan ts = TimeSpan.FromSeconds(time); - return !absolute - ? (ts.Hours == 0 ? ts.ToString(@"mm\mss\s") : ts.ToString(@"hh\hmm\mss\s")) - : ts.ToString(@"hh\:mm\:ss"); + var ts = TimeSpan.FromSeconds(time); + var totalHours = (int)ts.TotalHours; + var minutes = ts.Minutes; + var seconds = ts.Seconds; + + if (absolute) + { + return $"{totalHours:D2}:{minutes:D2}:{seconds:D2}"; + } + + return totalHours == 0 ? $"{minutes:D2}m{seconds:D2}s" : $"{totalHours}h{minutes:D2}m{seconds:D2}s"; } /// diff --git a/clash-meta/config/config.go b/clash-meta/config/config.go index 77fdd4d64d..f6c19a291b 100644 --- a/clash-meta/config/config.go +++ b/clash-meta/config/config.go @@ -292,6 +292,7 @@ type RawTun struct { ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"` EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"` + DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"` FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"` Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"` @@ -1552,6 +1553,7 @@ func parseTun(rawTun RawTun, general *General) error { ExcludePackage: rawTun.ExcludePackage, EndpointIndependentNat: rawTun.EndpointIndependentNat, UDPTimeout: rawTun.UDPTimeout, + DisableICMPForwarding: rawTun.DisableICMPForwarding, FileDescriptor: rawTun.FileDescriptor, Inet4RouteAddress: rawTun.Inet4RouteAddress, diff --git a/clash-meta/docs/config.yaml b/clash-meta/docs/config.yaml index 77992164d7..2f44e24d38 100644 --- a/clash-meta/docs/config.yaml +++ b/clash-meta/docs/config.yaml @@ -142,6 +142,7 @@ tun: # gso-max-size: 65536 # 通用分段卸载包的最大大小 auto-redirect: false # 自动配置 iptables 以重定向 TCP 连接。仅支持 Linux。带有 auto-redirect 的 auto-route 现在可以在路由器上按预期工作,无需干预。 # strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问 + # disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟 route-address-set: # 将指定规则集中的目标 IP CIDR 规则添加到防火墙, 不匹配的流量将绕过路由, 仅支持 Linux,且需要 nftables,`auto-route` 和 `auto-redirect` 已启用。 - ruleset-1 - ruleset-2 @@ -1554,6 +1555,7 @@ listeners: # - com.android.chrome # exclude-package: # 排除被路由的 Android 应用包名 # - com.android.captiveportallogin + # disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟 # 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理 # shadowsocks,vmess 入口配置(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理) # ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456 diff --git a/clash-meta/listener/config/tun.go b/clash-meta/listener/config/tun.go index 0efbc82789..0e26232984 100644 --- a/clash-meta/listener/config/tun.go +++ b/clash-meta/listener/config/tun.go @@ -48,6 +48,7 @@ type Tun struct { ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"` EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"` + DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"` FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"` Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"` @@ -186,6 +187,9 @@ func (t *Tun) Equal(other Tun) bool { if t.UDPTimeout != other.UDPTimeout { return false } + if t.DisableICMPForwarding != other.DisableICMPForwarding { + return false + } if t.FileDescriptor != other.FileDescriptor { return false } diff --git a/clash-meta/listener/inbound/tun.go b/clash-meta/listener/inbound/tun.go index e6ebb2a109..79004023a7 100644 --- a/clash-meta/listener/inbound/tun.go +++ b/clash-meta/listener/inbound/tun.go @@ -49,6 +49,7 @@ type TunOption struct { ExcludePackage []string `inbound:"exclude-package,omitempty"` EndpointIndependentNat bool `inbound:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `inbound:"udp-timeout,omitempty"` + DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"` FileDescriptor int `inbound:"file-descriptor,omitempty"` Inet4RouteAddress []netip.Prefix `inbound:"inet4-route-address,omitempty"` @@ -122,6 +123,7 @@ func NewTun(options *TunOption) (*Tun, error) { ExcludePackage: options.ExcludePackage, EndpointIndependentNat: options.EndpointIndependentNat, UDPTimeout: options.UDPTimeout, + DisableICMPForwarding: options.DisableICMPForwarding, FileDescriptor: options.FileDescriptor, Inet4RouteAddress: options.Inet4RouteAddress, diff --git a/clash-meta/listener/sing_tun/dns.go b/clash-meta/listener/sing_tun/dns.go index 0b8a3ebe5d..82a9fdb6c1 100644 --- a/clash-meta/listener/sing_tun/dns.go +++ b/clash-meta/listener/sing_tun/dns.go @@ -20,7 +20,8 @@ import ( type ListenerHandler struct { *sing.ListenerHandler - DnsAdds []netip.AddrPort + DnsAdds []netip.AddrPort + DisableICMPForwarding bool } func (h *ListenerHandler) ShouldHijackDns(targetAddr netip.AddrPort) bool { diff --git a/clash-meta/listener/sing_tun/prepare.go b/clash-meta/listener/sing_tun/prepare.go index b3e1e0b228..e59947b84b 100644 --- a/clash-meta/listener/sing_tun/prepare.go +++ b/clash-meta/listener/sing_tun/prepare.go @@ -17,7 +17,7 @@ import ( func (h *ListenerHandler) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) { switch network { case N.NetworkICMP: // our fork only send those type to PrepareConnection now - if resolver.IsFakeIP(destination.Addr) { // skip fakeip + if h.DisableICMPForwarding || resolver.IsFakeIP(destination.Addr) { // skip fakeip and if ICMP handling is disabled log.Infoln("[ICMP] %s %s --> %s using fake ping echo", network, source, destination) return nil, nil } diff --git a/clash-meta/listener/sing_tun/server.go b/clash-meta/listener/sing_tun/server.go index 6bee7ffc40..ccd12f42db 100644 --- a/clash-meta/listener/sing_tun/server.go +++ b/clash-meta/listener/sing_tun/server.go @@ -267,8 +267,9 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis } handler := &ListenerHandler{ - ListenerHandler: h, - DnsAdds: dnsAdds, + ListenerHandler: h, + DnsAdds: dnsAdds, + DisableICMPForwarding: options.DisableICMPForwarding, } l = &Listener{ closed: false, diff --git a/clash-nyanpasu/backend/Cargo.lock b/clash-nyanpasu/backend/Cargo.lock index ffcea316b9..f4a9dbeaa6 100644 --- a/clash-nyanpasu/backend/Cargo.lock +++ b/clash-nyanpasu/backend/Cargo.lock @@ -200,9 +200,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "ambassador" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b27ba24e4d8a188489d5a03c7fabc167a60809a383cdb4d15feb37479cd2a48" +checksum = "e68de4cdc6006162265d0957edb4a860fe4e711b1dc17a5746fd95f952f08285" dependencies = [ "itertools 0.10.5", "proc-macro2", @@ -858,7 +858,7 @@ dependencies = [ "bitflags 2.9.4", "cexpr", "clang-sys", - "itertools 0.10.5", + "itertools 0.11.0", "lazy_static", "lazycell", "log", diff --git a/clash-nyanpasu/frontend/interface/package.json b/clash-nyanpasu/frontend/interface/package.json index dce78dee0b..0c05058711 100644 --- a/clash-nyanpasu/frontend/interface/package.json +++ b/clash-nyanpasu/frontend/interface/package.json @@ -11,7 +11,7 @@ "build": "tsc" }, "dependencies": { - "@tanstack/react-query": "5.85.9", + "@tanstack/react-query": "5.87.1", "@tauri-apps/api": "2.8.0", "ahooks": "3.9.5", "dayjs": "1.11.18", diff --git a/clash-nyanpasu/frontend/nyanpasu/package.json b/clash-nyanpasu/frontend/nyanpasu/package.json index ff36887196..9da3298a08 100644 --- a/clash-nyanpasu/frontend/nyanpasu/package.json +++ b/clash-nyanpasu/frontend/nyanpasu/package.json @@ -32,7 +32,7 @@ "country-emoji": "1.5.6", "dayjs": "1.11.18", "framer-motion": "12.23.12", - "i18next": "25.4.2", + "i18next": "25.5.2", "jotai": "2.13.1", "json-schema": "0.4.0", "material-react-table": "3.2.1", @@ -56,9 +56,9 @@ "@csstools/normalize.css": "12.1.1", "@emotion/babel-plugin": "11.13.5", "@emotion/react": "11.14.0", - "@iconify/json": "2.2.381", + "@iconify/json": "2.2.382", "@monaco-editor/react": "4.7.0", - "@tanstack/react-query": "5.85.9", + "@tanstack/react-query": "5.87.1", "@tanstack/react-router": "1.131.35", "@tanstack/react-router-devtools": "1.131.35", "@tanstack/router-plugin": "1.131.35", diff --git a/clash-nyanpasu/package.json b/clash-nyanpasu/package.json index b395076d3f..e00777a8d3 100644 --- a/clash-nyanpasu/package.json +++ b/clash-nyanpasu/package.json @@ -98,7 +98,7 @@ "prettier-plugin-tailwindcss": "0.6.14", "prettier-plugin-toml": "2.0.6", "react-devtools": "6.1.5", - "stylelint": "16.23.1", + "stylelint": "16.24.0", "stylelint-config-html": "1.1.0", "stylelint-config-recess-order": "7.3.0", "stylelint-config-standard": "39.0.0", @@ -112,7 +112,7 @@ }, "packageManager": "pnpm@10.15.1", "engines": { - "node": "22.18.0" + "node": "22.19.0" }, "pnpm": { "overrides": { diff --git a/clash-nyanpasu/pnpm-lock.yaml b/clash-nyanpasu/pnpm-lock.yaml index 3765731c4e..028b23c35e 100644 --- a/clash-nyanpasu/pnpm-lock.yaml +++ b/clash-nyanpasu/pnpm-lock.yaml @@ -143,26 +143,26 @@ importers: specifier: 6.1.5 version: 6.1.5(bufferutil@4.0.8)(utf-8-validate@5.0.10) stylelint: - specifier: 16.23.1 - version: 16.23.1(typescript@5.9.2) + specifier: 16.24.0 + version: 16.24.0(typescript@5.9.2) stylelint-config-html: specifier: 1.1.0 - version: 1.1.0(postcss-html@1.8.0)(stylelint@16.23.1(typescript@5.9.2)) + version: 1.1.0(postcss-html@1.8.0)(stylelint@16.24.0(typescript@5.9.2)) stylelint-config-recess-order: specifier: 7.3.0 - version: 7.3.0(stylelint-order@7.0.0(stylelint@16.23.1(typescript@5.9.2)))(stylelint@16.23.1(typescript@5.9.2)) + version: 7.3.0(stylelint-order@7.0.0(stylelint@16.24.0(typescript@5.9.2)))(stylelint@16.24.0(typescript@5.9.2)) stylelint-config-standard: specifier: 39.0.0 - version: 39.0.0(stylelint@16.23.1(typescript@5.9.2)) + version: 39.0.0(stylelint@16.24.0(typescript@5.9.2)) stylelint-declaration-block-no-ignored-properties: specifier: 2.8.0 - version: 2.8.0(stylelint@16.23.1(typescript@5.9.2)) + version: 2.8.0(stylelint@16.24.0(typescript@5.9.2)) stylelint-order: specifier: 7.0.0 - version: 7.0.0(stylelint@16.23.1(typescript@5.9.2)) + version: 7.0.0(stylelint@16.24.0(typescript@5.9.2)) stylelint-scss: specifier: 6.12.1 - version: 6.12.1(stylelint@16.23.1(typescript@5.9.2)) + version: 6.12.1(stylelint@16.24.0(typescript@5.9.2)) tailwindcss: specifier: 4.1.13 version: 4.1.13 @@ -179,8 +179,8 @@ importers: frontend/interface: dependencies: '@tanstack/react-query': - specifier: 5.85.9 - version: 5.85.9(react@19.1.1) + specifier: 5.87.1 + version: 5.87.1(react@19.1.1) '@tauri-apps/api': specifier: 2.8.0 version: 2.8.0 @@ -279,8 +279,8 @@ importers: specifier: 12.23.12 version: 12.23.12(@emotion/is-prop-valid@1.3.0)(react-dom@19.1.1(react@19.1.1))(react@19.1.1) i18next: - specifier: 25.4.2 - version: 25.4.2(typescript@5.9.2) + specifier: 25.5.2 + version: 25.5.2(typescript@5.9.2) jotai: specifier: 2.13.1 version: 2.13.1(@babel/core@7.28.3)(@babel/template@7.27.2)(@types/react@19.1.12)(react@19.1.1) @@ -313,7 +313,7 @@ importers: version: 8.0.0(713a47822f182782b49fcf422d4af5f2) react-i18next: specifier: 15.7.3 - version: 15.7.3(i18next@25.4.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2) + version: 15.7.3(i18next@25.5.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2) react-markdown: specifier: 10.1.0 version: 10.1.0(@types/react@19.1.12)(react@19.1.1) @@ -346,14 +346,14 @@ importers: specifier: 11.14.0 version: 11.14.0(@types/react@19.1.12)(react@19.1.1) '@iconify/json': - specifier: 2.2.381 - version: 2.2.381 + specifier: 2.2.382 + version: 2.2.382 '@monaco-editor/react': specifier: 4.7.0 version: 4.7.0(monaco-editor@0.52.2)(react-dom@19.1.1(react@19.1.1))(react@19.1.1) '@tanstack/react-query': - specifier: 5.85.9 - version: 5.85.9(react@19.1.1) + specifier: 5.87.1 + version: 5.87.1(react@19.1.1) '@tanstack/react-router': specifier: 1.131.35 version: 1.131.35(react-dom@19.1.1(react@19.1.1))(react@19.1.1) @@ -512,7 +512,7 @@ importers: version: 6.0.0(react@19.1.1) react-i18next: specifier: 15.7.3 - version: 15.7.3(i18next@25.4.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2) + version: 15.7.3(i18next@25.5.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2) react-use: specifier: 17.6.0 version: 17.6.0(react-dom@19.1.1(react@19.1.1))(react@19.1.1) @@ -1812,8 +1812,8 @@ packages: prettier-plugin-ember-template-tag: optional: true - '@iconify/json@2.2.381': - resolution: {integrity: sha512-YXGLVTau1yq44krZmG4hfI4rIBzL2wXg9Yr6WQRoXBZ6ScB6bdoANEoLYKARGNAFyxoNsc1FtTkcHIlBdJc9uQ==} + '@iconify/json@2.2.382': + resolution: {integrity: sha512-1UT0ouWPVXNteS+kaQjtDvxKy/swWqB84fq9b+xbpE7nhgfak7ljYneWSXTDU+SyfL112F9978p7Mf3C3Q/8LQ==} '@iconify/types@2.0.0': resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} @@ -3032,11 +3032,11 @@ packages: resolution: {integrity: sha512-Wo1iKt2b9OT7d+YGhvEPD3DXvPv2etTusIMhMUoG7fbhmxcXCtIjJDEygy91Y2JFlwGyjqiBPRozme7UD8hoqg==} engines: {node: '>=12'} - '@tanstack/query-core@5.85.9': - resolution: {integrity: sha512-5fxb9vwyftYE6KFLhhhDyLr8NO75+Wpu7pmTo+TkwKmMX2oxZDoLwcqGP8ItKSpUMwk3urWgQDZfyWr5Jm9LsQ==} + '@tanstack/query-core@5.87.1': + resolution: {integrity: sha512-HOFHVvhOCprrWvtccSzc7+RNqpnLlZ5R6lTmngb8aq7b4rc2/jDT0w+vLdQ4lD9bNtQ+/A4GsFXy030Gk4ollA==} - '@tanstack/react-query@5.85.9': - resolution: {integrity: sha512-2T5zgSpcOZXGkH/UObIbIkGmUPQqZqn7esVQFXLOze622h4spgWf5jmvrqAo9dnI13/hyMcNsF1jsoDcb59nJQ==} + '@tanstack/react-query@5.87.1': + resolution: {integrity: sha512-YKauf8jfMowgAqcxj96AHs+Ux3m3bWT1oSVKamaRPXSnW2HqSznnTCEkAVqctF1e/W9R/mPcyzzINIgpOH94qg==} peerDependencies: react: ^18 || ^19 @@ -4049,8 +4049,8 @@ packages: resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==} engines: {node: '>=8'} - cacheable@1.10.3: - resolution: {integrity: sha512-M6p10iJ/VT0wT7TLIGUnm958oVrU2cUK8pQAVU21Zu7h8rbk/PeRtRWrvHJBql97Bhzk3g1N6+2VKC+Rjxna9Q==} + cacheable@1.10.4: + resolution: {integrity: sha512-Gd7ccIUkZ9TE2odLQVS+PDjIvQCdJKUlLdJRVvZu0aipj07Qfx+XIej7hhDrKGGoIxV5m5fT/kOJNJPQhQneRg==} call-bind-apply-helpers@1.0.1: resolution: {integrity: sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==} @@ -5215,8 +5215,8 @@ packages: engines: {node: '>= 0.4.0'} hasBin: true - file-entry-cache@10.1.3: - resolution: {integrity: sha512-D+w75Ub8T55yor7fPgN06rkCAUbAYw2vpxJmmjv/GDAcvCnv9g7IvHhIZoxzRZThrXPFI2maeY24pPbtyYU7Lg==} + file-entry-cache@10.1.4: + resolution: {integrity: sha512-5XRUFc0WTtUbjfGzEwXc42tiGxQHBmtbUG1h9L2apu4SulCGN3Hqm//9D6FAolf8MYNL7f/YlJl9vy08pj5JuA==} file-entry-cache@8.0.0: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} @@ -5248,8 +5248,8 @@ packages: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} - flat-cache@6.1.12: - resolution: {integrity: sha512-U+HqqpZPPXP5d24bWuRzjGqVqUcw64k4nZAbruniDwdRg0H10tvN7H6ku1tjhA4rg5B9GS3siEvwO2qjJJ6f8Q==} + flat-cache@6.1.13: + resolution: {integrity: sha512-gmtS2PaUjSPa4zjObEIn4WWliKyZzYljgxODBfxugpK6q6HU9ClXzgCJ+nlcPKY9Bt090ypTOLIFWkV0jbKFjw==} flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} @@ -5590,8 +5590,8 @@ packages: hyphenate-style-name@1.1.0: resolution: {integrity: sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw==} - i18next@25.4.2: - resolution: {integrity: sha512-gD4T25a6ovNXsfXY1TwHXXXLnD/K2t99jyYMCSimSCBnBRJVQr5j+VAaU83RJCPzrTGhVQ6dqIga66xO2rtd5g==} + i18next@25.5.2: + resolution: {integrity: sha512-lW8Zeh37i/o0zVr+NoCHfNnfvVw+M6FQbRp36ZZ/NyHDJ3NJVpp2HhAUyU9WafL5AssymNoOjMRB48mmx2P6Hw==} peerDependencies: typescript: ^5 peerDependenciesMeta: @@ -6111,8 +6111,8 @@ packages: keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - keyv@5.4.0: - resolution: {integrity: sha512-TMckyVjEoacG5IteUpUrOBsFORtheqziVyyY2dLUwg1jwTb8u48LX4TgmtogkNl9Y9unaEJ1luj10fGyjMGFOQ==} + keyv@5.5.0: + resolution: {integrity: sha512-QG7qR2tijh1ftOvClut4YKKg1iW6cx3GZsKoGyJPxHkGWK9oJhG9P3j5deP0QQOGDowBMVQFaP+Vm4NpGYvmIQ==} kind-of@6.0.3: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} @@ -7953,8 +7953,8 @@ packages: peerDependencies: stylelint: ^16.0.2 - stylelint@16.23.1: - resolution: {integrity: sha512-dNvDTsKV1U2YtiUDfe9d2gp902veFeo3ecCWdGlmLm2WFrAV0+L5LoOj/qHSBABQwMsZPJwfC4bf39mQm1S5zw==} + stylelint@16.24.0: + resolution: {integrity: sha512-7ksgz3zJaSbTUGr/ujMXvLVKdDhLbGl3R/3arNudH7z88+XZZGNLMTepsY28WlnvEFcuOmUe7fg40Q3lfhOfSQ==} engines: {node: '>=18.12.0'} hasBin: true @@ -10213,7 +10213,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@iconify/json@2.2.381': + '@iconify/json@2.2.382': dependencies: '@iconify/types': 2.0.0 pathe: 1.1.2 @@ -11327,11 +11327,11 @@ snapshots: dependencies: remove-accents: 0.5.0 - '@tanstack/query-core@5.85.9': {} + '@tanstack/query-core@5.87.1': {} - '@tanstack/react-query@5.85.9(react@19.1.1)': + '@tanstack/react-query@5.87.1(react@19.1.1)': dependencies: - '@tanstack/query-core': 5.85.9 + '@tanstack/query-core': 5.87.1 react: 19.1.1 '@tanstack/react-router-devtools@1.131.35(@tanstack/react-router@1.131.35(react-dom@19.1.1(react@19.1.1))(react@19.1.1))(@tanstack/router-core@1.131.35)(csstype@3.1.3)(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(solid-js@1.9.5)(tiny-invariant@1.3.3)': @@ -12510,10 +12510,10 @@ snapshots: normalize-url: 6.1.0 responselike: 2.0.1 - cacheable@1.10.3: + cacheable@1.10.4: dependencies: hookified: 1.11.0 - keyv: 5.4.0 + keyv: 5.5.0 call-bind-apply-helpers@1.0.1: dependencies: @@ -13928,9 +13928,9 @@ snapshots: figlet@1.8.2: {} - file-entry-cache@10.1.3: + file-entry-cache@10.1.4: dependencies: - flat-cache: 6.1.12 + flat-cache: 6.1.13 file-entry-cache@8.0.0: dependencies: @@ -13964,9 +13964,9 @@ snapshots: flatted: 3.3.3 keyv: 4.5.4 - flat-cache@6.1.12: + flat-cache@6.1.13: dependencies: - cacheable: 1.10.3 + cacheable: 1.10.4 flatted: 3.3.3 hookified: 1.11.0 @@ -14393,9 +14393,9 @@ snapshots: hyphenate-style-name@1.1.0: {} - i18next@25.4.2(typescript@5.9.2): + i18next@25.5.2(typescript@5.9.2): dependencies: - '@babel/runtime': 7.28.2 + '@babel/runtime': 7.28.3 optionalDependencies: typescript: 5.9.2 @@ -14843,7 +14843,7 @@ snapshots: dependencies: json-buffer: 3.0.1 - keyv@5.4.0: + keyv@5.5.0: dependencies: '@keyv/serialize': 1.1.0 @@ -16058,11 +16058,11 @@ snapshots: dependencies: react: 19.1.1 - react-i18next@15.7.3(i18next@25.4.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2): + react-i18next@15.7.3(i18next@25.5.2(typescript@5.9.2))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(typescript@5.9.2): dependencies: '@babel/runtime': 7.28.2 html-parse-stringify: 3.0.1 - i18next: 25.4.2(typescript@5.9.2) + i18next: 25.5.2(typescript@5.9.2) react: 19.1.1 optionalDependencies: react-dom: 19.1.1(react@19.1.1) @@ -16836,36 +16836,36 @@ snapshots: dependencies: inline-style-parser: 0.2.3 - stylelint-config-html@1.1.0(postcss-html@1.8.0)(stylelint@16.23.1(typescript@5.9.2)): + stylelint-config-html@1.1.0(postcss-html@1.8.0)(stylelint@16.24.0(typescript@5.9.2)): dependencies: postcss-html: 1.8.0 - stylelint: 16.23.1(typescript@5.9.2) + stylelint: 16.24.0(typescript@5.9.2) - stylelint-config-recess-order@7.3.0(stylelint-order@7.0.0(stylelint@16.23.1(typescript@5.9.2)))(stylelint@16.23.1(typescript@5.9.2)): + stylelint-config-recess-order@7.3.0(stylelint-order@7.0.0(stylelint@16.24.0(typescript@5.9.2)))(stylelint@16.24.0(typescript@5.9.2)): dependencies: - stylelint: 16.23.1(typescript@5.9.2) - stylelint-order: 7.0.0(stylelint@16.23.1(typescript@5.9.2)) + stylelint: 16.24.0(typescript@5.9.2) + stylelint-order: 7.0.0(stylelint@16.24.0(typescript@5.9.2)) - stylelint-config-recommended@17.0.0(stylelint@16.23.1(typescript@5.9.2)): + stylelint-config-recommended@17.0.0(stylelint@16.24.0(typescript@5.9.2)): dependencies: - stylelint: 16.23.1(typescript@5.9.2) + stylelint: 16.24.0(typescript@5.9.2) - stylelint-config-standard@39.0.0(stylelint@16.23.1(typescript@5.9.2)): + stylelint-config-standard@39.0.0(stylelint@16.24.0(typescript@5.9.2)): dependencies: - stylelint: 16.23.1(typescript@5.9.2) - stylelint-config-recommended: 17.0.0(stylelint@16.23.1(typescript@5.9.2)) + stylelint: 16.24.0(typescript@5.9.2) + stylelint-config-recommended: 17.0.0(stylelint@16.24.0(typescript@5.9.2)) - stylelint-declaration-block-no-ignored-properties@2.8.0(stylelint@16.23.1(typescript@5.9.2)): + stylelint-declaration-block-no-ignored-properties@2.8.0(stylelint@16.24.0(typescript@5.9.2)): dependencies: - stylelint: 16.23.1(typescript@5.9.2) + stylelint: 16.24.0(typescript@5.9.2) - stylelint-order@7.0.0(stylelint@16.23.1(typescript@5.9.2)): + stylelint-order@7.0.0(stylelint@16.24.0(typescript@5.9.2)): dependencies: postcss: 8.5.6 postcss-sorting: 9.1.0(postcss@8.5.6) - stylelint: 16.23.1(typescript@5.9.2) + stylelint: 16.24.0(typescript@5.9.2) - stylelint-scss@6.12.1(stylelint@16.23.1(typescript@5.9.2)): + stylelint-scss@6.12.1(stylelint@16.24.0(typescript@5.9.2)): dependencies: css-tree: 3.1.0 is-plain-object: 5.0.0 @@ -16875,9 +16875,9 @@ snapshots: postcss-resolve-nested-selector: 0.1.6 postcss-selector-parser: 7.1.0 postcss-value-parser: 4.2.0 - stylelint: 16.23.1(typescript@5.9.2) + stylelint: 16.24.0(typescript@5.9.2) - stylelint@16.23.1(typescript@5.9.2): + stylelint@16.24.0(typescript@5.9.2): dependencies: '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) '@csstools/css-tokenizer': 3.0.4 @@ -16892,7 +16892,7 @@ snapshots: debug: 4.4.1 fast-glob: 3.3.3 fastest-levenshtein: 1.0.16 - file-entry-cache: 10.1.3 + file-entry-cache: 10.1.4 global-modules: 2.0.0 globby: 11.1.0 globjoin: 0.1.4 diff --git a/lede/target/linux/generic/backport-6.6/786-v6.10-net-sfp-add-quirk-for-another-multigig-RollBall-tran.patch b/lede/target/linux/generic/backport-6.6/786-v6.10-net-sfp-add-quirk-for-another-multigig-RollBall-tran.patch new file mode 100644 index 0000000000..9e368c8d3c --- /dev/null +++ b/lede/target/linux/generic/backport-6.6/786-v6.10-net-sfp-add-quirk-for-another-multigig-RollBall-tran.patch @@ -0,0 +1,30 @@ +From 1c77c721916ae108c2c5865986735bfe92000908 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Marek=20Beh=C3=BAn?= +Date: Tue, 9 Apr 2024 09:30:16 +0200 +Subject: [PATCH] net: sfp: add quirk for another multigig RollBall transceiver +MIME-Version: 1.0 +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: 8bit + +Add quirk for another RollBall copper transceiver: Turris RTSFP-2.5G, +containing 2.5g capable RTL8221B PHY. + +Signed-off-by: Marek Behún +Signed-off-by: Eric Woudstra + +Reviewed-by: Russell King (Oracle) +Signed-off-by: David S. Miller +--- + drivers/net/phy/sfp.c | 1 + + 1 file changed, 1 insertion(+) + +--- a/drivers/net/phy/sfp.c ++++ b/drivers/net/phy/sfp.c +@@ -505,6 +505,7 @@ static const struct sfp_quirk sfp_quirks + SFP_QUIRK_M("OEM", "SFP-2.5G-BX10-U", sfp_quirk_2500basex), + SFP_QUIRK_F("OEM", "RTSFP-10", sfp_fixup_rollball_cc), + SFP_QUIRK_F("OEM", "RTSFP-10G", sfp_fixup_rollball_cc), ++ SFP_QUIRK_F("Turris", "RTSFP-2.5G", sfp_fixup_rollball), + SFP_QUIRK_F("Turris", "RTSFP-10", sfp_fixup_rollball), + SFP_QUIRK_F("Turris", "RTSFP-10G", sfp_fixup_rollball), + }; diff --git a/lede/target/linux/generic/pending-6.12/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch b/lede/target/linux/generic/pending-6.12/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch new file mode 100644 index 0000000000..dedb5b1a9f --- /dev/null +++ b/lede/target/linux/generic/pending-6.12/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch @@ -0,0 +1,28 @@ +From ddbf0e78a8b20ec18d314d31336a0230fdc9b394 Mon Sep 17 00:00:00 2001 +From: Aleksander Jan Bajkowski +Date: Sun, 31 Aug 2025 12:59:07 +0200 +Subject: net: sfp: add quirk for FLYPRO copper SFP+ module + +Add quirk for a copper SFP that identifies itself as "FLYPRO" +"SFP-10GT-CS-30M". It uses RollBall protocol to talk to the PHY. + +Signed-off-by: Aleksander Jan Bajkowski +Reviewed-by: Russell King (Oracle) +Link: https://patch.msgid.link/20250831105910.3174-1-olek2@wp.pl +Signed-off-by: Jakub Kicinski +--- + drivers/net/phy/sfp.c | 3 +++ + 1 file changed, 3 insertions(+) + +--- a/drivers/net/phy/sfp.c ++++ b/drivers/net/phy/sfp.c +@@ -474,6 +474,9 @@ static const struct sfp_quirk sfp_quirks + SFP_QUIRK("ALCATELLUCENT", "3FE46541AA", sfp_quirk_2500basex, + sfp_fixup_nokia), + ++ // FLYPRO SFP-10GT-CS-30M uses Rollball protocol to talk to the PHY. ++ SFP_QUIRK_F("FLYPRO", "SFP-10GT-CS-30M", sfp_fixup_rollball), ++ + // Fiberstore SFP-10G-T doesn't identify as copper, uses the Rollball + // protocol to talk to the PHY and needs 4 sec wait before probing the + // PHY. diff --git a/lede/target/linux/generic/pending-6.6/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch b/lede/target/linux/generic/pending-6.6/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch new file mode 100644 index 0000000000..a155d4aa97 --- /dev/null +++ b/lede/target/linux/generic/pending-6.6/750-net-sfp-add-quirk-for-FlyPro-10Gbase-T-module.patch @@ -0,0 +1,28 @@ +From ddbf0e78a8b20ec18d314d31336a0230fdc9b394 Mon Sep 17 00:00:00 2001 +From: Aleksander Jan Bajkowski +Date: Sun, 31 Aug 2025 12:59:07 +0200 +Subject: net: sfp: add quirk for FLYPRO copper SFP+ module + +Add quirk for a copper SFP that identifies itself as "FLYPRO" +"SFP-10GT-CS-30M". It uses RollBall protocol to talk to the PHY. + +Signed-off-by: Aleksander Jan Bajkowski +Reviewed-by: Russell King (Oracle) +Link: https://patch.msgid.link/20250831105910.3174-1-olek2@wp.pl +Signed-off-by: Jakub Kicinski +--- + drivers/net/phy/sfp.c | 3 +++ + 1 file changed, 3 insertions(+) + +--- a/drivers/net/phy/sfp.c ++++ b/drivers/net/phy/sfp.c +@@ -459,6 +459,9 @@ static const struct sfp_quirk sfp_quirks + SFP_QUIRK("ALCATELLUCENT", "3FE46541AA", sfp_quirk_2500basex, + sfp_fixup_long_startup), + ++ // FLYPRO SFP-10GT-CS-30M uses Rollball protocol to talk to the PHY. ++ SFP_QUIRK_F("FLYPRO", "SFP-10GT-CS-30M", sfp_fixup_rollball), ++ + // Fiberstore SFP-10G-T doesn't identify as copper, uses the Rollball + // protocol to talk to the PHY and needs 4 sec wait before probing the + // PHY. diff --git a/mieru/pkg/protocol/mux.go b/mieru/pkg/protocol/mux.go index 03d505e573..20f45d87d3 100644 --- a/mieru/pkg/protocol/mux.go +++ b/mieru/pkg/protocol/mux.go @@ -38,7 +38,7 @@ import ( ) const ( - idleUnderlayTickerInterval = 5 * time.Second + underlayCleanInterval = 5 * time.Second ) // Mux manages the sessions and underlays. @@ -85,7 +85,7 @@ func NewMux(isClinet bool) *Mux { chAccept: make(chan net.Conn, sessionChanCapacity), acceptErr: make(chan error), done: make(chan struct{}), - cleaner: time.NewTicker(idleUnderlayTickerInterval), + cleaner: time.NewTicker(underlayCleanInterval), } mux.ctx, mux.ctxCancelFunc = context.WithCancel(context.Background()) @@ -479,10 +479,10 @@ func (m *Mux) acceptUnderlayLoop(ctx context.Context, properties UnderlayPropert } log.Infof("Mux is listening to endpoint %s %s", network, laddr) underlay := &PacketUnderlay{ - baseUnderlay: *newBaseUnderlay(false, properties.MTU()), - conn: conn, - idleSessionTicker: time.NewTicker(idleSessionTickerInterval), - users: m.users, + baseUnderlay: *newBaseUnderlay(false, properties.MTU()), + conn: conn, + sessionCleanTicker: time.NewTicker(sessionCleanInterval), + users: m.users, } log.Infof("Created new server underlay %v", underlay) m.mu.Lock() @@ -564,10 +564,11 @@ func (m *Mux) serverWrapTCPConn(rawConn net.Conn, mtu int, users map[string]*app blocks = append(blocks, blocksFromUser...) } return &StreamUnderlay{ - baseUnderlay: *newBaseUnderlay(false, mtu), - conn: rawConn, - candidates: blocks, - users: users, + baseUnderlay: *newBaseUnderlay(false, mtu), + conn: rawConn, + candidates: blocks, + sessionCleanTicker: time.NewTicker(sessionCleanInterval), + users: users, } } diff --git a/mieru/pkg/protocol/underlay_base.go b/mieru/pkg/protocol/underlay_base.go index a956f12f4d..9d9373ee7f 100644 --- a/mieru/pkg/protocol/underlay_base.go +++ b/mieru/pkg/protocol/underlay_base.go @@ -21,6 +21,7 @@ import ( "io" "net" "sync" + "time" "github.com/enfein/mieru/v3/pkg/appctl/appctlpb" "github.com/enfein/mieru/v3/pkg/common" @@ -28,7 +29,10 @@ import ( "github.com/enfein/mieru/v3/pkg/stderror" ) -const sessionChanCapacity = 64 +const ( + sessionChanCapacity = 64 + sessionCleanInterval = 5 * time.Second +) // baseUnderlay contains a partial implementation of underlay. type baseUnderlay struct { diff --git a/mieru/pkg/protocol/underlay_packet.go b/mieru/pkg/protocol/underlay_packet.go index bababbe599..5c44cd2cae 100644 --- a/mieru/pkg/protocol/underlay_packet.go +++ b/mieru/pkg/protocol/underlay_packet.go @@ -38,8 +38,7 @@ const ( packetOverhead = cipher.DefaultNonceSize + MetadataLength + cipher.DefaultOverhead*2 packetNonHeaderPosition = cipher.DefaultNonceSize + MetadataLength + cipher.DefaultOverhead - idleSessionTickerInterval = 5 * time.Second - idleSessionTimeout = time.Minute + idleSessionTimeout = time.Minute readOneSegmentTimeout = 5 * time.Second ) @@ -51,7 +50,7 @@ type PacketUnderlay struct { baseUnderlay conn net.PacketConn - idleSessionTicker *time.Ticker + sessionCleanTicker *time.Ticker // ---- client fields ---- serverAddr net.Addr @@ -91,11 +90,11 @@ func NewPacketUnderlay(ctx context.Context, network, addr string, mtu int, block return nil, fmt.Errorf("ApplyUDPControls() failed: %w", err) } u := &PacketUnderlay{ - baseUnderlay: *newBaseUnderlay(true, mtu), - conn: conn, - idleSessionTicker: time.NewTicker(idleSessionTickerInterval), - serverAddr: remoteAddr, - block: block, + baseUnderlay: *newBaseUnderlay(true, mtu), + conn: conn, + sessionCleanTicker: time.NewTicker(sessionCleanInterval), + serverAddr: remoteAddr, + block: block, } // The block cipher expires after this time. u.scheduler.SetRemainingTime(cipher.KeyRefreshInterval / 2) @@ -123,7 +122,7 @@ func (u *PacketUnderlay) Close() error { } log.Debugf("Closing %v", u) - u.idleSessionTicker.Stop() + u.sessionCleanTicker.Stop() u.baseUnderlay.Close() return u.conn.Close() } @@ -175,13 +174,13 @@ func (u *PacketUnderlay) RunEventLoop(ctx context.Context) error { for { select { case <-ctx.Done(): - u.closeIdleSessions() + u.cleanSessions() return nil case <-u.done: - u.closeIdleSessions() + u.cleanSessions() return nil - case <-u.idleSessionTicker.C: - u.closeIdleSessions() + case <-u.sessionCleanTicker.C: + u.cleanSessions() default: } seg, addr, err := u.readOneSegment() @@ -706,7 +705,7 @@ func (u *PacketUnderlay) writeOneSegment(seg *segment, addr net.Addr) error { return nil } -func (u *PacketUnderlay) closeIdleSessions() { +func (u *PacketUnderlay) cleanSessions() { u.sessionMap.Range(func(k, v any) bool { session := v.(*Session) select { diff --git a/mieru/pkg/protocol/underlay_stream.go b/mieru/pkg/protocol/underlay_stream.go index 9d19f2a952..9096aa93a7 100644 --- a/mieru/pkg/protocol/underlay_stream.go +++ b/mieru/pkg/protocol/underlay_stream.go @@ -50,6 +50,8 @@ type StreamUnderlay struct { // When isClient is true, there must be exactly 1 element in the slice. candidates []cipher.BlockCipher + sessionCleanTicker *time.Ticker + // ---- server fields ---- users map[string]*appctlpb.User } @@ -75,9 +77,10 @@ func NewStreamUnderlay(ctx context.Context, dialer apicommon.Dialer, network, ad return nil, fmt.Errorf("DialContext() failed: %w", err) } t := &StreamUnderlay{ - baseUnderlay: *newBaseUnderlay(true, mtu), - conn: conn, - candidates: []cipher.BlockCipher{block}, + baseUnderlay: *newBaseUnderlay(true, mtu), + conn: conn, + candidates: []cipher.BlockCipher{block}, + sessionCleanTicker: time.NewTicker(sessionCleanInterval), } return t, nil } @@ -99,6 +102,7 @@ func (t *StreamUnderlay) Close() error { } log.Debugf("Closing %v", t) + t.sessionCleanTicker.Stop() t.baseUnderlay.Close() return t.conn.Close() } @@ -157,9 +161,13 @@ func (t *StreamUnderlay) RunEventLoop(ctx context.Context) error { for { select { case <-ctx.Done(): + t.cleanSessions() return nil case <-t.done: + t.cleanSessions() return nil + case <-t.sessionCleanTicker.C: + t.cleanSessions() default: } seg, err := t.readOneSegment() @@ -636,3 +644,18 @@ func (t *StreamUnderlay) drainAfterError() { log.Debugf("%v read at least %d bytes after stream error", t, n) } } + +func (t *StreamUnderlay) cleanSessions() { + t.sessionMap.Range(func(k, v any) bool { + session := v.(*Session) + select { + case <-session.closedChan: + log.Debugf("Found closed %v", session) + if err := t.RemoveSession(session); err != nil { + log.Debugf("%v RemoveSession() failed: %v", t, err) + } + default: + } + return true + }) +} diff --git a/mihomo/config/config.go b/mihomo/config/config.go index 77fdd4d64d..f6c19a291b 100644 --- a/mihomo/config/config.go +++ b/mihomo/config/config.go @@ -292,6 +292,7 @@ type RawTun struct { ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"` EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"` + DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"` FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"` Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"` @@ -1552,6 +1553,7 @@ func parseTun(rawTun RawTun, general *General) error { ExcludePackage: rawTun.ExcludePackage, EndpointIndependentNat: rawTun.EndpointIndependentNat, UDPTimeout: rawTun.UDPTimeout, + DisableICMPForwarding: rawTun.DisableICMPForwarding, FileDescriptor: rawTun.FileDescriptor, Inet4RouteAddress: rawTun.Inet4RouteAddress, diff --git a/mihomo/docs/config.yaml b/mihomo/docs/config.yaml index 77992164d7..2f44e24d38 100644 --- a/mihomo/docs/config.yaml +++ b/mihomo/docs/config.yaml @@ -142,6 +142,7 @@ tun: # gso-max-size: 65536 # 通用分段卸载包的最大大小 auto-redirect: false # 自动配置 iptables 以重定向 TCP 连接。仅支持 Linux。带有 auto-redirect 的 auto-route 现在可以在路由器上按预期工作,无需干预。 # strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问 + # disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟 route-address-set: # 将指定规则集中的目标 IP CIDR 规则添加到防火墙, 不匹配的流量将绕过路由, 仅支持 Linux,且需要 nftables,`auto-route` 和 `auto-redirect` 已启用。 - ruleset-1 - ruleset-2 @@ -1554,6 +1555,7 @@ listeners: # - com.android.chrome # exclude-package: # 排除被路由的 Android 应用包名 # - com.android.captiveportallogin + # disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟 # 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理 # shadowsocks,vmess 入口配置(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理) # ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456 diff --git a/mihomo/listener/config/tun.go b/mihomo/listener/config/tun.go index 0efbc82789..0e26232984 100644 --- a/mihomo/listener/config/tun.go +++ b/mihomo/listener/config/tun.go @@ -48,6 +48,7 @@ type Tun struct { ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"` EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"` + DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"` FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"` Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"` @@ -186,6 +187,9 @@ func (t *Tun) Equal(other Tun) bool { if t.UDPTimeout != other.UDPTimeout { return false } + if t.DisableICMPForwarding != other.DisableICMPForwarding { + return false + } if t.FileDescriptor != other.FileDescriptor { return false } diff --git a/mihomo/listener/inbound/tun.go b/mihomo/listener/inbound/tun.go index e6ebb2a109..79004023a7 100644 --- a/mihomo/listener/inbound/tun.go +++ b/mihomo/listener/inbound/tun.go @@ -49,6 +49,7 @@ type TunOption struct { ExcludePackage []string `inbound:"exclude-package,omitempty"` EndpointIndependentNat bool `inbound:"endpoint-independent-nat,omitempty"` UDPTimeout int64 `inbound:"udp-timeout,omitempty"` + DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"` FileDescriptor int `inbound:"file-descriptor,omitempty"` Inet4RouteAddress []netip.Prefix `inbound:"inet4-route-address,omitempty"` @@ -122,6 +123,7 @@ func NewTun(options *TunOption) (*Tun, error) { ExcludePackage: options.ExcludePackage, EndpointIndependentNat: options.EndpointIndependentNat, UDPTimeout: options.UDPTimeout, + DisableICMPForwarding: options.DisableICMPForwarding, FileDescriptor: options.FileDescriptor, Inet4RouteAddress: options.Inet4RouteAddress, diff --git a/mihomo/listener/sing_tun/dns.go b/mihomo/listener/sing_tun/dns.go index 0b8a3ebe5d..82a9fdb6c1 100644 --- a/mihomo/listener/sing_tun/dns.go +++ b/mihomo/listener/sing_tun/dns.go @@ -20,7 +20,8 @@ import ( type ListenerHandler struct { *sing.ListenerHandler - DnsAdds []netip.AddrPort + DnsAdds []netip.AddrPort + DisableICMPForwarding bool } func (h *ListenerHandler) ShouldHijackDns(targetAddr netip.AddrPort) bool { diff --git a/mihomo/listener/sing_tun/prepare.go b/mihomo/listener/sing_tun/prepare.go index b3e1e0b228..e59947b84b 100644 --- a/mihomo/listener/sing_tun/prepare.go +++ b/mihomo/listener/sing_tun/prepare.go @@ -17,7 +17,7 @@ import ( func (h *ListenerHandler) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) { switch network { case N.NetworkICMP: // our fork only send those type to PrepareConnection now - if resolver.IsFakeIP(destination.Addr) { // skip fakeip + if h.DisableICMPForwarding || resolver.IsFakeIP(destination.Addr) { // skip fakeip and if ICMP handling is disabled log.Infoln("[ICMP] %s %s --> %s using fake ping echo", network, source, destination) return nil, nil } diff --git a/mihomo/listener/sing_tun/server.go b/mihomo/listener/sing_tun/server.go index 6bee7ffc40..ccd12f42db 100644 --- a/mihomo/listener/sing_tun/server.go +++ b/mihomo/listener/sing_tun/server.go @@ -267,8 +267,9 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis } handler := &ListenerHandler{ - ListenerHandler: h, - DnsAdds: dnsAdds, + ListenerHandler: h, + DnsAdds: dnsAdds, + DisableICMPForwarding: options.DisableICMPForwarding, } l = &Listener{ closed: false, diff --git a/nekobox-android/.github/workflows/preview.yml b/nekobox-android/.github/workflows/preview.yml index 0f326ef100..a6df3a164b 100644 --- a/nekobox-android/.github/workflows/preview.yml +++ b/nekobox-android/.github/workflows/preview.yml @@ -24,7 +24,7 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' uses: actions/setup-go@v5 with: - go-version: ^1.24 + go-version: ^1.25 - name: Native Build if: steps.cache.outputs.cache-hit != 'true' run: ./run lib core diff --git a/nekobox-android/.github/workflows/release.yml b/nekobox-android/.github/workflows/release.yml index 0cd234122f..7aecc1c058 100644 --- a/nekobox-android/.github/workflows/release.yml +++ b/nekobox-android/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' uses: actions/setup-go@v5 with: - go-version: ^1.24 + go-version: ^1.25 - name: Native Build if: steps.cache.outputs.cache-hit != 'true' run: ./run lib core diff --git a/nekobox-android/app/src/main/java/com/wireguard/crypto/Curve25519.java b/nekobox-android/app/src/main/java/com/wireguard/crypto/Curve25519.java deleted file mode 100644 index 55f2809af9..0000000000 --- a/nekobox-android/app/src/main/java/com/wireguard/crypto/Curve25519.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * Copyright © 2016 Southern Storm Software, Pty Ltd. - * Copyright © 2017-2019 WireGuard LLC. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -package com.wireguard.crypto; - -import androidx.annotation.Nullable; - -import java.util.Arrays; - -/** - * Implementation of Curve25519 ECDH. - *

- * This implementation was imported to WireGuard from noise-java: - * https://github.com/rweather/noise-java - *

- * This implementation is based on that from arduinolibs: - * https://github.com/rweather/arduinolibs - *

- * Differences in this version are due to using 26-bit limbs for the - * representation instead of the 8/16/32-bit limbs in the original. - *

- * References: http://cr.yp.to/ecdh.html, RFC 7748 - */ -@SuppressWarnings({"MagicNumber", "NonConstantFieldWithUpperCaseName", "SuspiciousNameCombination"}) -public final class Curve25519 { - // Numbers modulo 2^255 - 19 are broken up into ten 26-bit words. - private static final int NUM_LIMBS_255BIT = 10; - private static final int NUM_LIMBS_510BIT = 20; - - private final int[] A; - private final int[] AA; - private final int[] B; - private final int[] BB; - private final int[] C; - private final int[] CB; - private final int[] D; - private final int[] DA; - private final int[] E; - private final long[] t1; - private final int[] t2; - private final int[] x_1; - private final int[] x_2; - private final int[] x_3; - private final int[] z_2; - private final int[] z_3; - - /** - * Constructs the temporary state holder for Curve25519 evaluation. - */ - private Curve25519() { - // Allocate memory for all of the temporary variables we will need. - x_1 = new int[NUM_LIMBS_255BIT]; - x_2 = new int[NUM_LIMBS_255BIT]; - x_3 = new int[NUM_LIMBS_255BIT]; - z_2 = new int[NUM_LIMBS_255BIT]; - z_3 = new int[NUM_LIMBS_255BIT]; - A = new int[NUM_LIMBS_255BIT]; - B = new int[NUM_LIMBS_255BIT]; - C = new int[NUM_LIMBS_255BIT]; - D = new int[NUM_LIMBS_255BIT]; - E = new int[NUM_LIMBS_255BIT]; - AA = new int[NUM_LIMBS_255BIT]; - BB = new int[NUM_LIMBS_255BIT]; - DA = new int[NUM_LIMBS_255BIT]; - CB = new int[NUM_LIMBS_255BIT]; - t1 = new long[NUM_LIMBS_510BIT]; - t2 = new int[NUM_LIMBS_510BIT]; - } - - /** - * Conditional swap of two values. - * - * @param select Set to 1 to swap, 0 to leave as-is. - * @param x The first value. - * @param y The second value. - */ - private static void cswap(int select, final int[] x, final int[] y) { - select = -select; - for (int index = 0; index < NUM_LIMBS_255BIT; ++index) { - final int dummy = select & (x[index] ^ y[index]); - x[index] ^= dummy; - y[index] ^= dummy; - } - } - - /** - * Evaluates the Curve25519 curve. - * - * @param result Buffer to place the result of the evaluation into. - * @param offset Offset into the result buffer. - * @param privateKey The private key to use in the evaluation. - * @param publicKey The public key to use in the evaluation, or null - * if the base point of the curve should be used. - */ - public static void eval(final byte[] result, final int offset, - final byte[] privateKey, @Nullable final byte[] publicKey) { - final Curve25519 state = new Curve25519(); - try { - // Unpack the public key value. If null, use 9 as the base point. - Arrays.fill(state.x_1, 0); - if (publicKey != null) { - // Convert the input value from little-endian into 26-bit limbs. - for (int index = 0; index < 32; ++index) { - final int bit = (index * 8) % 26; - final int word = (index * 8) / 26; - final int value = publicKey[index] & 0xFF; - if (bit <= (26 - 8)) { - state.x_1[word] |= value << bit; - } else { - state.x_1[word] |= value << bit; - state.x_1[word] &= 0x03FFFFFF; - state.x_1[word + 1] |= value >> (26 - bit); - } - } - - // Just in case, we reduce the number modulo 2^255 - 19 to - // make sure that it is in range of the field before we start. - // This eliminates values between 2^255 - 19 and 2^256 - 1. - state.reduceQuick(state.x_1); - state.reduceQuick(state.x_1); - } else { - state.x_1[0] = 9; - } - - // Initialize the other temporary variables. - Arrays.fill(state.x_2, 0); // x_2 = 1 - state.x_2[0] = 1; - Arrays.fill(state.z_2, 0); // z_2 = 0 - System.arraycopy(state.x_1, 0, state.x_3, 0, state.x_1.length); // x_3 = x_1 - Arrays.fill(state.z_3, 0); // z_3 = 1 - state.z_3[0] = 1; - - // Evaluate the curve for every bit of the private key. - state.evalCurve(privateKey); - - // Compute x_2 * (z_2 ^ (p - 2)) where p = 2^255 - 19. - state.recip(state.z_3, state.z_2); - state.mul(state.x_2, state.x_2, state.z_3); - - // Convert x_2 into little-endian in the result buffer. - for (int index = 0; index < 32; ++index) { - final int bit = (index * 8) % 26; - final int word = (index * 8) / 26; - if (bit <= (26 - 8)) - result[offset + index] = (byte) (state.x_2[word] >> bit); - else - result[offset + index] = (byte) ((state.x_2[word] >> bit) | (state.x_2[word + 1] << (26 - bit))); - } - } finally { - // Clean up all temporary state before we exit. - state.destroy(); - } - } - - /** - * Subtracts two numbers modulo 2^255 - 19. - * - * @param result The result. - * @param x The first number to subtract. - * @param y The second number to subtract. - */ - private static void sub(final int[] result, final int[] x, final int[] y) { - int index; - int borrow; - - // Subtract y from x to generate the intermediate result. - borrow = 0; - for (index = 0; index < NUM_LIMBS_255BIT; ++index) { - borrow = x[index] - y[index] - ((borrow >> 26) & 0x01); - result[index] = borrow & 0x03FFFFFF; - } - - // If we had a borrow, then the result has gone negative and we - // have to add 2^255 - 19 to the result to make it positive again. - // The top bits of "borrow" will be all 1's if there is a borrow - // or it will be all 0's if there was no borrow. Easiest is to - // conditionally subtract 19 and then mask off the high bits. - borrow = result[0] - ((-((borrow >> 26) & 0x01)) & 19); - result[0] = borrow & 0x03FFFFFF; - for (index = 1; index < NUM_LIMBS_255BIT; ++index) { - borrow = result[index] - ((borrow >> 26) & 0x01); - result[index] = borrow & 0x03FFFFFF; - } - result[NUM_LIMBS_255BIT - 1] &= 0x001FFFFF; - } - - /** - * Adds two numbers modulo 2^255 - 19. - * - * @param result The result. - * @param x The first number to add. - * @param y The second number to add. - */ - private void add(final int[] result, final int[] x, final int[] y) { - int carry = x[0] + y[0]; - result[0] = carry & 0x03FFFFFF; - for (int index = 1; index < NUM_LIMBS_255BIT; ++index) { - carry = (carry >> 26) + x[index] + y[index]; - result[index] = carry & 0x03FFFFFF; - } - reduceQuick(result); - } - - /** - * Destroy all sensitive data in this object. - */ - private void destroy() { - // Destroy all temporary variables. - Arrays.fill(x_1, 0); - Arrays.fill(x_2, 0); - Arrays.fill(x_3, 0); - Arrays.fill(z_2, 0); - Arrays.fill(z_3, 0); - Arrays.fill(A, 0); - Arrays.fill(B, 0); - Arrays.fill(C, 0); - Arrays.fill(D, 0); - Arrays.fill(E, 0); - Arrays.fill(AA, 0); - Arrays.fill(BB, 0); - Arrays.fill(DA, 0); - Arrays.fill(CB, 0); - Arrays.fill(t1, 0L); - Arrays.fill(t2, 0); - } - - /** - * Evaluates the curve for every bit in a secret key. - * - * @param s The 32-byte secret key. - */ - private void evalCurve(final byte[] s) { - int sposn = 31; - int sbit = 6; - int svalue = s[sposn] | 0x40; - int swap = 0; - - // Iterate over all 255 bits of "s" from the highest to the lowest. - // We ignore the high bit of the 256-bit representation of "s". - while (true) { - // Conditional swaps on entry to this bit but only if we - // didn't swap on the previous bit. - final int select = (svalue >> sbit) & 0x01; - swap ^= select; - cswap(swap, x_2, x_3); - cswap(swap, z_2, z_3); - swap = select; - - // Evaluate the curve. - add(A, x_2, z_2); // A = x_2 + z_2 - square(AA, A); // AA = A^2 - sub(B, x_2, z_2); // B = x_2 - z_2 - square(BB, B); // BB = B^2 - sub(E, AA, BB); // E = AA - BB - add(C, x_3, z_3); // C = x_3 + z_3 - sub(D, x_3, z_3); // D = x_3 - z_3 - mul(DA, D, A); // DA = D * A - mul(CB, C, B); // CB = C * B - add(x_3, DA, CB); // x_3 = (DA + CB)^2 - square(x_3, x_3); - sub(z_3, DA, CB); // z_3 = x_1 * (DA - CB)^2 - square(z_3, z_3); - mul(z_3, z_3, x_1); - mul(x_2, AA, BB); // x_2 = AA * BB - mulA24(z_2, E); // z_2 = E * (AA + a24 * E) - add(z_2, z_2, AA); - mul(z_2, z_2, E); - - // Move onto the next lower bit of "s". - if (sbit > 0) { - --sbit; - } else if (sposn == 0) { - break; - } else if (sposn == 1) { - --sposn; - svalue = s[sposn] & 0xF8; - sbit = 7; - } else { - --sposn; - svalue = s[sposn]; - sbit = 7; - } - } - - // Final conditional swaps. - cswap(swap, x_2, x_3); - cswap(swap, z_2, z_3); - } - - /** - * Multiplies two numbers modulo 2^255 - 19. - * - * @param result The result. - * @param x The first number to multiply. - * @param y The second number to multiply. - */ - private void mul(final int[] result, final int[] x, final int[] y) { - // Multiply the two numbers to create the intermediate result. - long v = x[0]; - for (int i = 0; i < NUM_LIMBS_255BIT; ++i) { - t1[i] = v * y[i]; - } - for (int i = 1; i < NUM_LIMBS_255BIT; ++i) { - v = x[i]; - for (int j = 0; j < (NUM_LIMBS_255BIT - 1); ++j) { - t1[i + j] += v * y[j]; - } - t1[i + NUM_LIMBS_255BIT - 1] = v * y[NUM_LIMBS_255BIT - 1]; - } - - // Propagate carries and convert back into 26-bit words. - v = t1[0]; - t2[0] = ((int) v) & 0x03FFFFFF; - for (int i = 1; i < NUM_LIMBS_510BIT; ++i) { - v = (v >> 26) + t1[i]; - t2[i] = ((int) v) & 0x03FFFFFF; - } - - // Reduce the result modulo 2^255 - 19. - reduce(result, t2, NUM_LIMBS_255BIT); - } - - /** - * Multiplies a number by the a24 constant, modulo 2^255 - 19. - * - * @param result The result. - * @param x The number to multiply by a24. - */ - private void mulA24(final int[] result, final int[] x) { - final long a24 = 121665; - long carry = 0; - for (int index = 0; index < NUM_LIMBS_255BIT; ++index) { - carry += a24 * x[index]; - t2[index] = ((int) carry) & 0x03FFFFFF; - carry >>= 26; - } - t2[NUM_LIMBS_255BIT] = ((int) carry) & 0x03FFFFFF; - reduce(result, t2, 1); - } - - /** - * Raise x to the power of (2^250 - 1). - * - * @param result The result. Must not overlap with x. - * @param x The argument. - */ - private void pow250(final int[] result, final int[] x) { - // The big-endian hexadecimal expansion of (2^250 - 1) is: - // 03FFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF - // - // The naive implementation needs to do 2 multiplications per 1 bit and - // 1 multiplication per 0 bit. We can improve upon this by creating a - // pattern 0000000001 ... 0000000001. If we square and multiply the - // pattern by itself we can turn the pattern into the partial results - // 0000000011 ... 0000000011, 0000000111 ... 0000000111, etc. - // This averages out to about 1.1 multiplications per 1 bit instead of 2. - - // Build a pattern of 250 bits in length of repeated copies of 0000000001. - square(A, x); - for (int j = 0; j < 9; ++j) - square(A, A); - mul(result, A, x); - for (int i = 0; i < 23; ++i) { - for (int j = 0; j < 10; ++j) - square(A, A); - mul(result, result, A); - } - - // Multiply bit-shifted versions of the 0000000001 pattern into - // the result to "fill in" the gaps in the pattern. - square(A, result); - mul(result, result, A); - for (int j = 0; j < 8; ++j) { - square(A, A); - mul(result, result, A); - } - } - - /** - * Computes the reciprocal of a number modulo 2^255 - 19. - * - * @param result The result. Must not overlap with x. - * @param x The argument. - */ - private void recip(final int[] result, final int[] x) { - // The reciprocal is the same as x ^ (p - 2) where p = 2^255 - 19. - // The big-endian hexadecimal expansion of (p - 2) is: - // 7FFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFEB - // Start with the 250 upper bits of the expansion of (p - 2). - pow250(result, x); - - // Deal with the 5 lowest bits of (p - 2), 01011, from highest to lowest. - square(result, result); - square(result, result); - mul(result, result, x); - square(result, result); - square(result, result); - mul(result, result, x); - square(result, result); - mul(result, result, x); - } - - /** - * Reduce a number modulo 2^255 - 19. - * - * @param result The result. - * @param x The value to be reduced. This array will be - * modified during the reduction. - * @param size The number of limbs in the high order half of x. - */ - private void reduce(final int[] result, final int[] x, final int size) { - // Calculate (x mod 2^255) + ((x / 2^255) * 19) which will - // either produce the answer we want or it will produce a - // value of the form "answer + j * (2^255 - 19)". There are - // 5 left-over bits in the top-most limb of the bottom half. - int carry = 0; - int limb = x[NUM_LIMBS_255BIT - 1] >> 21; - x[NUM_LIMBS_255BIT - 1] &= 0x001FFFFF; - for (int index = 0; index < size; ++index) { - limb += x[NUM_LIMBS_255BIT + index] << 5; - carry += (limb & 0x03FFFFFF) * 19 + x[index]; - x[index] = carry & 0x03FFFFFF; - limb >>= 26; - carry >>= 26; - } - if (size < NUM_LIMBS_255BIT) { - // The high order half of the number is short; e.g. for mulA24(). - // Propagate the carry through the rest of the low order part. - for (int index = size; index < NUM_LIMBS_255BIT; ++index) { - carry += x[index]; - x[index] = carry & 0x03FFFFFF; - carry >>= 26; - } - } - - // The "j" value may still be too large due to the final carry-out. - // We must repeat the reduction. If we already have the answer, - // then this won't do any harm but we must still do the calculation - // to preserve the overall timing. The "j" value will be between - // 0 and 19, which means that the carry we care about is in the - // top 5 bits of the highest limb of the bottom half. - carry = (x[NUM_LIMBS_255BIT - 1] >> 21) * 19; - x[NUM_LIMBS_255BIT - 1] &= 0x001FFFFF; - for (int index = 0; index < NUM_LIMBS_255BIT; ++index) { - carry += x[index]; - result[index] = carry & 0x03FFFFFF; - carry >>= 26; - } - - // At this point "x" will either be the answer or it will be the - // answer plus (2^255 - 19). Perform a trial subtraction to - // complete the reduction process. - reduceQuick(result); - } - - /** - * Reduces a number modulo 2^255 - 19 where it is known that the - * number can be reduced with only 1 trial subtraction. - * - * @param x The number to reduce, and the result. - */ - private void reduceQuick(final int[] x) { - // Perform a trial subtraction of (2^255 - 19) from "x" which is - // equivalent to adding 19 and subtracting 2^255. We add 19 here; - // the subtraction of 2^255 occurs in the next step. - int carry = 19; - for (int index = 0; index < NUM_LIMBS_255BIT; ++index) { - carry += x[index]; - t2[index] = carry & 0x03FFFFFF; - carry >>= 26; - } - - // If there was a borrow, then the original "x" is the correct answer. - // If there was no borrow, then "t2" is the correct answer. Select the - // correct answer but do it in a way that instruction timing will not - // reveal which value was selected. Borrow will occur if bit 21 of - // "t2" is zero. Turn the bit into a selection mask. - final int mask = -((t2[NUM_LIMBS_255BIT - 1] >> 21) & 0x01); - final int nmask = ~mask; - t2[NUM_LIMBS_255BIT - 1] &= 0x001FFFFF; - for (int index = 0; index < NUM_LIMBS_255BIT; ++index) - x[index] = (x[index] & nmask) | (t2[index] & mask); - } - - /** - * Squares a number modulo 2^255 - 19. - * - * @param result The result. - * @param x The number to square. - */ - private void square(final int[] result, final int[] x) { - mul(result, x, x); - } -} diff --git a/nekobox-android/app/src/main/java/com/wireguard/crypto/Ed25519.java b/nekobox-android/app/src/main/java/com/wireguard/crypto/Ed25519.java deleted file mode 100644 index a60babfbb4..0000000000 --- a/nekobox-android/app/src/main/java/com/wireguard/crypto/Ed25519.java +++ /dev/null @@ -1,2508 +0,0 @@ -/* - * Copyright © 2020 WireGuard LLC. All Rights Reserved. - * Copyright 2017 Google Inc. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package com.wireguard.crypto; - -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.Arrays; - -/** - * Implementation of Ed25519 signature verification. - * - *

This implementation is based on the ed25519/ref10 implementation in NaCl.

- * - *

It implements this twisted Edwards curve: - * - *

- * -x^2 + y^2 = 1 + (-121665 / 121666 mod 2^255-19)*x^2*y^2
- * 
- * - * @see Bernstein D.J., Birkner P., Joye M., Lange - * T., Peters C. (2008) Twisted Edwards Curves - * @see Hisil H., Wong K.KH., Carter G., Dawson E. - * (2008) Twisted Edwards Curves Revisited - */ -public final class Ed25519 { - - // d = -121665 / 121666 mod 2^255-19 - private static final long[] D; - // 2d - private static final long[] D2; - // 2^((p-1)/4) mod p where p = 2^255-19 - private static final long[] SQRTM1; - - /** - * Base point for the Edwards twisted curve = (x, 4/5) and its exponentiations. B_TABLE[i][j] = - * (j+1)*256^i*B for i in [0, 32) and j in [0, 8). Base point B = B_TABLE[0][0] - */ - private static final CachedXYT[][] B_TABLE; - private static final CachedXYT[] B2; - - private static final BigInteger P_BI = - BigInteger.valueOf(2).pow(255).subtract(BigInteger.valueOf(19)); - private static final BigInteger D_BI = - BigInteger.valueOf(-121665).multiply(BigInteger.valueOf(121666).modInverse(P_BI)).mod(P_BI); - private static final BigInteger D2_BI = BigInteger.valueOf(2).multiply(D_BI).mod(P_BI); - private static final BigInteger SQRTM1_BI = - BigInteger.valueOf(2).modPow(P_BI.subtract(BigInteger.ONE).divide(BigInteger.valueOf(4)), P_BI); - - private Ed25519() { - } - - private static class Point { - private BigInteger x; - private BigInteger y; - } - - private static BigInteger recoverX(BigInteger y) { - // x^2 = (y^2 - 1) / (d * y^2 + 1) mod 2^255-19 - BigInteger xx = - y.pow(2) - .subtract(BigInteger.ONE) - .multiply(D_BI.multiply(y.pow(2)).add(BigInteger.ONE).modInverse(P_BI)); - BigInteger x = xx.modPow(P_BI.add(BigInteger.valueOf(3)).divide(BigInteger.valueOf(8)), P_BI); - if (!x.pow(2).subtract(xx).mod(P_BI).equals(BigInteger.ZERO)) { - x = x.multiply(SQRTM1_BI).mod(P_BI); - } - if (x.testBit(0)) { - x = P_BI.subtract(x); - } - return x; - } - - private static Point edwards(Point a, Point b) { - Point o = new Point(); - BigInteger xxyy = D_BI.multiply(a.x.multiply(b.x).multiply(a.y).multiply(b.y)).mod(P_BI); - o.x = - (a.x.multiply(b.y).add(b.x.multiply(a.y))) - .multiply(BigInteger.ONE.add(xxyy).modInverse(P_BI)) - .mod(P_BI); - o.y = - (a.y.multiply(b.y).add(a.x.multiply(b.x))) - .multiply(BigInteger.ONE.subtract(xxyy).modInverse(P_BI)) - .mod(P_BI); - return o; - } - - private static byte[] toLittleEndian(BigInteger n) { - byte[] b = new byte[32]; - byte[] nBytes = n.toByteArray(); - System.arraycopy(nBytes, 0, b, 32 - nBytes.length, nBytes.length); - for (int i = 0; i < b.length / 2; i++) { - byte t = b[i]; - b[i] = b[b.length - i - 1]; - b[b.length - i - 1] = t; - } - return b; - } - - private static CachedXYT getCachedXYT(Point p) { - return new CachedXYT( - Field25519.expand(toLittleEndian(p.y.add(p.x).mod(P_BI))), - Field25519.expand(toLittleEndian(p.y.subtract(p.x).mod(P_BI))), - Field25519.expand(toLittleEndian(D2_BI.multiply(p.x).multiply(p.y).mod(P_BI)))); - } - - static { - Point b = new Point(); - b.y = BigInteger.valueOf(4).multiply(BigInteger.valueOf(5).modInverse(P_BI)).mod(P_BI); - b.x = recoverX(b.y); - - D = Field25519.expand(toLittleEndian(D_BI)); - D2 = Field25519.expand(toLittleEndian(D2_BI)); - SQRTM1 = Field25519.expand(toLittleEndian(SQRTM1_BI)); - - Point bi = b; - B_TABLE = new CachedXYT[32][8]; - for (int i = 0; i < 32; i++) { - Point bij = bi; - for (int j = 0; j < 8; j++) { - B_TABLE[i][j] = getCachedXYT(bij); - bij = edwards(bij, bi); - } - for (int j = 0; j < 8; j++) { - bi = edwards(bi, bi); - } - } - bi = b; - Point b2 = edwards(b, b); - B2 = new CachedXYT[8]; - for (int i = 0; i < 8; i++) { - B2[i] = getCachedXYT(bi); - bi = edwards(bi, b2); - } - } - - private static final int PUBLIC_KEY_LEN = Field25519.FIELD_LEN; - private static final int SIGNATURE_LEN = Field25519.FIELD_LEN * 2; - - /** - * Defines field 25519 function based on curve25519-donna C - * implementation (mostly identical). - * - *

Field elements are written as an array of signed, 64-bit limbs (an array of longs), least - * significant first. The value of the field element is: - * - *

-     * x[0] + 2^26·x[1] + 2^51·x[2] + 2^77·x[3] + 2^102·x[4] + 2^128·x[5] + 2^153·x[6] + 2^179·x[7] +
-     * 2^204·x[8] + 2^230·x[9],
-     * 
- * - *

i.e. the limbs are 26, 25, 26, 25, ... bits wide. - */ - private static final class Field25519 { - /** - * During Field25519 computation, the mixed radix representation may be in different forms: - *

    - *
  • Reduced-size form: the array has size at most 10. - *
  • Non-reduced-size form: the array is not reduced modulo 2^255 - 19 and has size at most - * 19. - *
- *

- * TODO(quannguyen): - *

    - *
  • Clarify ill-defined terminologies. - *
  • The reduction procedure is different from DJB's paper - * (http://cr.yp.to/ecdh/curve25519-20060209.pdf). The coefficients after reducing degree and - * reducing coefficients aren't guaranteed to be in range {-2^25, ..., 2^25}. We should check to - * see what's going on. - *
  • Consider using method mult() everywhere and making product() private. - *
- */ - - static final int FIELD_LEN = 32; - static final int LIMB_CNT = 10; - private static final long TWO_TO_25 = 1 << 25; - private static final long TWO_TO_26 = TWO_TO_25 << 1; - - private static final int[] EXPAND_START = {0, 3, 6, 9, 12, 16, 19, 22, 25, 28}; - private static final int[] EXPAND_SHIFT = {0, 2, 3, 5, 6, 0, 1, 3, 4, 6}; - private static final int[] MASK = {0x3ffffff, 0x1ffffff}; - private static final int[] SHIFT = {26, 25}; - - /** - * Sums two numbers: output = in1 + in2 - *

- * On entry: in1, in2 are in reduced-size form. - */ - static void sum(long[] output, long[] in1, long[] in2) { - for (int i = 0; i < LIMB_CNT; i++) { - output[i] = in1[i] + in2[i]; - } - } - - /** - * Sums two numbers: output += in - *

- * On entry: in is in reduced-size form. - */ - static void sum(long[] output, long[] in) { - sum(output, output, in); - } - - /** - * Find the difference of two numbers: output = in1 - in2 - * (note the order of the arguments!). - *

- * On entry: in1, in2 are in reduced-size form. - */ - static void sub(long[] output, long[] in1, long[] in2) { - for (int i = 0; i < LIMB_CNT; i++) { - output[i] = in1[i] - in2[i]; - } - } - - /** - * Find the difference of two numbers: output = in - output - * (note the order of the arguments!). - *

- * On entry: in, output are in reduced-size form. - */ - static void sub(long[] output, long[] in) { - sub(output, in, output); - } - - /** - * Multiply a number by a scalar: output = in * scalar - */ - static void scalarProduct(long[] output, long[] in, long scalar) { - for (int i = 0; i < LIMB_CNT; i++) { - output[i] = in[i] * scalar; - } - } - - /** - * Multiply two numbers: out = in2 * in - *

- * output must be distinct to both inputs. The inputs are reduced coefficient form, - * the output is not. - *

- * out[x] <= 14 * the largest product of the input limbs. - */ - static void product(long[] out, long[] in2, long[] in) { - out[0] = in2[0] * in[0]; - out[1] = in2[0] * in[1] - + in2[1] * in[0]; - out[2] = 2 * in2[1] * in[1] - + in2[0] * in[2] - + in2[2] * in[0]; - out[3] = in2[1] * in[2] - + in2[2] * in[1] - + in2[0] * in[3] - + in2[3] * in[0]; - out[4] = in2[2] * in[2] - + 2 * (in2[1] * in[3] + in2[3] * in[1]) - + in2[0] * in[4] - + in2[4] * in[0]; - out[5] = in2[2] * in[3] - + in2[3] * in[2] - + in2[1] * in[4] - + in2[4] * in[1] - + in2[0] * in[5] - + in2[5] * in[0]; - out[6] = 2 * (in2[3] * in[3] + in2[1] * in[5] + in2[5] * in[1]) - + in2[2] * in[4] - + in2[4] * in[2] - + in2[0] * in[6] - + in2[6] * in[0]; - out[7] = in2[3] * in[4] - + in2[4] * in[3] - + in2[2] * in[5] - + in2[5] * in[2] - + in2[1] * in[6] - + in2[6] * in[1] - + in2[0] * in[7] - + in2[7] * in[0]; - out[8] = in2[4] * in[4] - + 2 * (in2[3] * in[5] + in2[5] * in[3] + in2[1] * in[7] + in2[7] * in[1]) - + in2[2] * in[6] - + in2[6] * in[2] - + in2[0] * in[8] - + in2[8] * in[0]; - out[9] = in2[4] * in[5] - + in2[5] * in[4] - + in2[3] * in[6] - + in2[6] * in[3] - + in2[2] * in[7] - + in2[7] * in[2] - + in2[1] * in[8] - + in2[8] * in[1] - + in2[0] * in[9] - + in2[9] * in[0]; - out[10] = - 2 * (in2[5] * in[5] + in2[3] * in[7] + in2[7] * in[3] + in2[1] * in[9] + in2[9] * in[1]) - + in2[4] * in[6] - + in2[6] * in[4] - + in2[2] * in[8] - + in2[8] * in[2]; - out[11] = in2[5] * in[6] - + in2[6] * in[5] - + in2[4] * in[7] - + in2[7] * in[4] - + in2[3] * in[8] - + in2[8] * in[3] - + in2[2] * in[9] - + in2[9] * in[2]; - out[12] = in2[6] * in[6] - + 2 * (in2[5] * in[7] + in2[7] * in[5] + in2[3] * in[9] + in2[9] * in[3]) - + in2[4] * in[8] - + in2[8] * in[4]; - out[13] = in2[6] * in[7] - + in2[7] * in[6] - + in2[5] * in[8] - + in2[8] * in[5] - + in2[4] * in[9] - + in2[9] * in[4]; - out[14] = 2 * (in2[7] * in[7] + in2[5] * in[9] + in2[9] * in[5]) - + in2[6] * in[8] - + in2[8] * in[6]; - out[15] = in2[7] * in[8] - + in2[8] * in[7] - + in2[6] * in[9] - + in2[9] * in[6]; - out[16] = in2[8] * in[8] - + 2 * (in2[7] * in[9] + in2[9] * in[7]); - out[17] = in2[8] * in[9] - + in2[9] * in[8]; - out[18] = 2 * in2[9] * in[9]; - } - - /** - * Reduce a field element by calling reduceSizeByModularReduction and reduceCoefficients. - * - * @param input An input array of any length. If the array has 19 elements, it will be used as - * temporary buffer and its contents changed. - * @param output An output array of size LIMB_CNT. After the call |output[i]| < 2^26 will hold. - */ - static void reduce(long[] input, long[] output) { - long[] tmp; - if (input.length == 19) { - tmp = input; - } else { - tmp = new long[19]; - System.arraycopy(input, 0, tmp, 0, input.length); - } - reduceSizeByModularReduction(tmp); - reduceCoefficients(tmp); - System.arraycopy(tmp, 0, output, 0, LIMB_CNT); - } - - /** - * Reduce a long form to a reduced-size form by taking the input mod 2^255 - 19. - *

- * On entry: |output[i]| < 14*2^54 - * On exit: |output[0..8]| < 280*2^54 - */ - static void reduceSizeByModularReduction(long[] output) { - // The coefficients x[10], x[11],..., x[18] are eliminated by reduction modulo 2^255 - 19. - // For example, the coefficient x[18] is multiplied by 19 and added to the coefficient x[8]. - // - // Each of these shifts and adds ends up multiplying the value by 19. - // - // For output[0..8], the absolute entry value is < 14*2^54 and we add, at most, 19*14*2^54 thus, - // on exit, |output[0..8]| < 280*2^54. - output[8] += output[18] << 4; - output[8] += output[18] << 1; - output[8] += output[18]; - output[7] += output[17] << 4; - output[7] += output[17] << 1; - output[7] += output[17]; - output[6] += output[16] << 4; - output[6] += output[16] << 1; - output[6] += output[16]; - output[5] += output[15] << 4; - output[5] += output[15] << 1; - output[5] += output[15]; - output[4] += output[14] << 4; - output[4] += output[14] << 1; - output[4] += output[14]; - output[3] += output[13] << 4; - output[3] += output[13] << 1; - output[3] += output[13]; - output[2] += output[12] << 4; - output[2] += output[12] << 1; - output[2] += output[12]; - output[1] += output[11] << 4; - output[1] += output[11] << 1; - output[1] += output[11]; - output[0] += output[10] << 4; - output[0] += output[10] << 1; - output[0] += output[10]; - } - - /** - * Reduce all coefficients of the short form input so that |x| < 2^26. - *

- * On entry: |output[i]| < 280*2^54 - */ - static void reduceCoefficients(long[] output) { - output[10] = 0; - - for (int i = 0; i < LIMB_CNT; i += 2) { - long over = output[i] / TWO_TO_26; - // The entry condition (that |output[i]| < 280*2^54) means that over is, at most, 280*2^28 in - // the first iteration of this loop. This is added to the next limb and we can approximate the - // resulting bound of that limb by 281*2^54. - output[i] -= over << 26; - output[i + 1] += over; - - // For the first iteration, |output[i+1]| < 281*2^54, thus |over| < 281*2^29. When this is - // added to the next limb, the resulting bound can be approximated as 281*2^54. - // - // For subsequent iterations of the loop, 281*2^54 remains a conservative bound and no - // overflow occurs. - over = output[i + 1] / TWO_TO_25; - output[i + 1] -= over << 25; - output[i + 2] += over; - } - // Now |output[10]| < 281*2^29 and all other coefficients are reduced. - output[0] += output[10] << 4; - output[0] += output[10] << 1; - output[0] += output[10]; - - output[10] = 0; - // Now output[1..9] are reduced, and |output[0]| < 2^26 + 19*281*2^29 so |over| will be no more - // than 2^16. - long over = output[0] / TWO_TO_26; - output[0] -= over << 26; - output[1] += over; - // Now output[0,2..9] are reduced, and |output[1]| < 2^25 + 2^16 < 2^26. The bound on - // |output[1]| is sufficient to meet our needs. - } - - /** - * A helpful wrapper around {@ref Field25519#product}: output = in * in2. - *

- * On entry: |in[i]| < 2^27 and |in2[i]| < 2^27. - *

- * The output is reduced degree (indeed, one need only provide storage for 10 limbs) and - * |output[i]| < 2^26. - */ - static void mult(long[] output, long[] in, long[] in2) { - long[] t = new long[19]; - product(t, in, in2); - // |t[i]| < 2^26 - reduce(t, output); - } - - /** - * Square a number: out = in**2 - *

- * output must be distinct from the input. The inputs are reduced coefficient form, the output is - * not. - *

- * out[x] <= 14 * the largest product of the input limbs. - */ - private static void squareInner(long[] out, long[] in) { - out[0] = in[0] * in[0]; - out[1] = 2 * in[0] * in[1]; - out[2] = 2 * (in[1] * in[1] + in[0] * in[2]); - out[3] = 2 * (in[1] * in[2] + in[0] * in[3]); - out[4] = in[2] * in[2] - + 4 * in[1] * in[3] - + 2 * in[0] * in[4]; - out[5] = 2 * (in[2] * in[3] + in[1] * in[4] + in[0] * in[5]); - out[6] = 2 * (in[3] * in[3] + in[2] * in[4] + in[0] * in[6] + 2 * in[1] * in[5]); - out[7] = 2 * (in[3] * in[4] + in[2] * in[5] + in[1] * in[6] + in[0] * in[7]); - out[8] = in[4] * in[4] - + 2 * (in[2] * in[6] + in[0] * in[8] + 2 * (in[1] * in[7] + in[3] * in[5])); - out[9] = 2 * (in[4] * in[5] + in[3] * in[6] + in[2] * in[7] + in[1] * in[8] + in[0] * in[9]); - out[10] = 2 * (in[5] * in[5] - + in[4] * in[6] - + in[2] * in[8] - + 2 * (in[3] * in[7] + in[1] * in[9])); - out[11] = 2 * (in[5] * in[6] + in[4] * in[7] + in[3] * in[8] + in[2] * in[9]); - out[12] = in[6] * in[6] - + 2 * (in[4] * in[8] + 2 * (in[5] * in[7] + in[3] * in[9])); - out[13] = 2 * (in[6] * in[7] + in[5] * in[8] + in[4] * in[9]); - out[14] = 2 * (in[7] * in[7] + in[6] * in[8] + 2 * in[5] * in[9]); - out[15] = 2 * (in[7] * in[8] + in[6] * in[9]); - out[16] = in[8] * in[8] + 4 * in[7] * in[9]; - out[17] = 2 * in[8] * in[9]; - out[18] = 2 * in[9] * in[9]; - } - - /** - * Returns in^2. - *

- * On entry: The |in| argument is in reduced coefficients form and |in[i]| < 2^27. - *

- * On exit: The |output| argument is in reduced coefficients form (indeed, one need only provide - * storage for 10 limbs) and |out[i]| < 2^26. - */ - static void square(long[] output, long[] in) { - long[] t = new long[19]; - squareInner(t, in); - // |t[i]| < 14*2^54 because the largest product of two limbs will be < 2^(27+27) and SquareInner - // adds together, at most, 14 of those products. - reduce(t, output); - } - - /** - * Takes a little-endian, 32-byte number and expands it into mixed radix form. - */ - static long[] expand(byte[] input) { - long[] output = new long[LIMB_CNT]; - for (int i = 0; i < LIMB_CNT; i++) { - output[i] = ((((long) (input[EXPAND_START[i]] & 0xff)) - | ((long) (input[EXPAND_START[i] + 1] & 0xff)) << 8 - | ((long) (input[EXPAND_START[i] + 2] & 0xff)) << 16 - | ((long) (input[EXPAND_START[i] + 3] & 0xff)) << 24) >> EXPAND_SHIFT[i]) & MASK[i & 1]; - } - return output; - } - - /** - * Takes a fully reduced mixed radix form number and contract it into a little-endian, 32-byte - * array. - *

- * On entry: |input_limbs[i]| < 2^26 - */ - @SuppressWarnings("NarrowingCompoundAssignment") - static byte[] contract(long[] inputLimbs) { - long[] input = Arrays.copyOf(inputLimbs, LIMB_CNT); - for (int j = 0; j < 2; j++) { - for (int i = 0; i < 9; i++) { - // This calculation is a time-invariant way to make input[i] non-negative by borrowing - // from the next-larger limb. - int carry = -(int) ((input[i] & (input[i] >> 31)) >> SHIFT[i & 1]); - input[i] = input[i] + (carry << SHIFT[i & 1]); - input[i + 1] -= carry; - } - - // There's no greater limb for input[9] to borrow from, but we can multiply by 19 and borrow - // from input[0], which is valid mod 2^255-19. - { - int carry = -(int) ((input[9] & (input[9] >> 31)) >> 25); - input[9] += (carry << 25); - input[0] -= (carry * 19); - } - - // After the first iteration, input[1..9] are non-negative and fit within 25 or 26 bits, - // depending on position. However, input[0] may be negative. - } - - // The first borrow-propagation pass above ended with every limb except (possibly) input[0] - // non-negative. - // - // If input[0] was negative after the first pass, then it was because of a carry from input[9]. - // On entry, input[9] < 2^26 so the carry was, at most, one, since (2**26-1) >> 25 = 1. Thus - // input[0] >= -19. - // - // In the second pass, each limb is decreased by at most one. Thus the second borrow-propagation - // pass could only have wrapped around to decrease input[0] again if the first pass left - // input[0] negative *and* input[1] through input[9] were all zero. In that case, input[1] is - // now 2^25 - 1, and this last borrow-propagation step will leave input[1] non-negative. - { - int carry = -(int) ((input[0] & (input[0] >> 31)) >> 26); - input[0] += (carry << 26); - input[1] -= carry; - } - - // All input[i] are now non-negative. However, there might be values between 2^25 and 2^26 in a - // limb which is, nominally, 25 bits wide. - for (int j = 0; j < 2; j++) { - for (int i = 0; i < 9; i++) { - int carry = (int) (input[i] >> SHIFT[i & 1]); - input[i] &= MASK[i & 1]; - input[i + 1] += carry; - } - } - - { - int carry = (int) (input[9] >> 25); - input[9] &= 0x1ffffff; - input[0] += 19 * carry; - } - - // If the first carry-chain pass, just above, ended up with a carry from input[9], and that - // caused input[0] to be out-of-bounds, then input[0] was < 2^26 + 2*19, because the carry was, - // at most, two. - // - // If the second pass carried from input[9] again then input[0] is < 2*19 and the input[9] -> - // input[0] carry didn't push input[0] out of bounds. - - // It still remains the case that input might be between 2^255-19 and 2^255. In this case, - // input[1..9] must take their maximum value and input[0] must be >= (2^255-19) & 0x3ffffff, - // which is 0x3ffffed. - int mask = gte((int) input[0], 0x3ffffed); - for (int i = 1; i < LIMB_CNT; i++) { - mask &= eq((int) input[i], MASK[i & 1]); - } - - // mask is either 0xffffffff (if input >= 2^255-19) and zero otherwise. Thus this conditionally - // subtracts 2^255-19. - input[0] -= mask & 0x3ffffed; - input[1] -= mask & 0x1ffffff; - for (int i = 2; i < LIMB_CNT; i += 2) { - input[i] -= mask & 0x3ffffff; - input[i + 1] -= mask & 0x1ffffff; - } - - for (int i = 0; i < LIMB_CNT; i++) { - input[i] <<= EXPAND_SHIFT[i]; - } - byte[] output = new byte[FIELD_LEN]; - for (int i = 0; i < LIMB_CNT; i++) { - output[EXPAND_START[i]] |= input[i] & 0xff; - output[EXPAND_START[i] + 1] |= (input[i] >> 8) & 0xff; - output[EXPAND_START[i] + 2] |= (input[i] >> 16) & 0xff; - output[EXPAND_START[i] + 3] |= (input[i] >> 24) & 0xff; - } - return output; - } - - /** - * Computes inverse of z = z(2^255 - 21) - *

- * Shamelessly copied from agl's code which was shamelessly copied from djb's code. Only the - * comment format and the variable namings are different from those. - */ - static void inverse(long[] out, long[] z) { - long[] z2 = new long[Field25519.LIMB_CNT]; - long[] z9 = new long[Field25519.LIMB_CNT]; - long[] z11 = new long[Field25519.LIMB_CNT]; - long[] z2To5Minus1 = new long[Field25519.LIMB_CNT]; - long[] z2To10Minus1 = new long[Field25519.LIMB_CNT]; - long[] z2To20Minus1 = new long[Field25519.LIMB_CNT]; - long[] z2To50Minus1 = new long[Field25519.LIMB_CNT]; - long[] z2To100Minus1 = new long[Field25519.LIMB_CNT]; - long[] t0 = new long[Field25519.LIMB_CNT]; - long[] t1 = new long[Field25519.LIMB_CNT]; - - square(z2, z); // 2 - square(t1, z2); // 4 - square(t0, t1); // 8 - mult(z9, t0, z); // 9 - mult(z11, z9, z2); // 11 - square(t0, z11); // 22 - mult(z2To5Minus1, t0, z9); // 2^5 - 2^0 = 31 - - square(t0, z2To5Minus1); // 2^6 - 2^1 - square(t1, t0); // 2^7 - 2^2 - square(t0, t1); // 2^8 - 2^3 - square(t1, t0); // 2^9 - 2^4 - square(t0, t1); // 2^10 - 2^5 - mult(z2To10Minus1, t0, z2To5Minus1); // 2^10 - 2^0 - - square(t0, z2To10Minus1); // 2^11 - 2^1 - square(t1, t0); // 2^12 - 2^2 - for (int i = 2; i < 10; i += 2) { // 2^20 - 2^10 - square(t0, t1); - square(t1, t0); - } - mult(z2To20Minus1, t1, z2To10Minus1); // 2^20 - 2^0 - - square(t0, z2To20Minus1); // 2^21 - 2^1 - square(t1, t0); // 2^22 - 2^2 - for (int i = 2; i < 20; i += 2) { // 2^40 - 2^20 - square(t0, t1); - square(t1, t0); - } - mult(t0, t1, z2To20Minus1); // 2^40 - 2^0 - - square(t1, t0); // 2^41 - 2^1 - square(t0, t1); // 2^42 - 2^2 - for (int i = 2; i < 10; i += 2) { // 2^50 - 2^10 - square(t1, t0); - square(t0, t1); - } - mult(z2To50Minus1, t0, z2To10Minus1); // 2^50 - 2^0 - - square(t0, z2To50Minus1); // 2^51 - 2^1 - square(t1, t0); // 2^52 - 2^2 - for (int i = 2; i < 50; i += 2) { // 2^100 - 2^50 - square(t0, t1); - square(t1, t0); - } - mult(z2To100Minus1, t1, z2To50Minus1); // 2^100 - 2^0 - - square(t1, z2To100Minus1); // 2^101 - 2^1 - square(t0, t1); // 2^102 - 2^2 - for (int i = 2; i < 100; i += 2) { // 2^200 - 2^100 - square(t1, t0); - square(t0, t1); - } - mult(t1, t0, z2To100Minus1); // 2^200 - 2^0 - - square(t0, t1); // 2^201 - 2^1 - square(t1, t0); // 2^202 - 2^2 - for (int i = 2; i < 50; i += 2) { // 2^250 - 2^50 - square(t0, t1); - square(t1, t0); - } - mult(t0, t1, z2To50Minus1); // 2^250 - 2^0 - - square(t1, t0); // 2^251 - 2^1 - square(t0, t1); // 2^252 - 2^2 - square(t1, t0); // 2^253 - 2^3 - square(t0, t1); // 2^254 - 2^4 - square(t1, t0); // 2^255 - 2^5 - mult(out, t1, z11); // 2^255 - 21 - } - - - /** - * Returns 0xffffffff iff a == b and zero otherwise. - */ - private static int eq(int a, int b) { - a = ~(a ^ b); - a &= a << 16; - a &= a << 8; - a &= a << 4; - a &= a << 2; - a &= a << 1; - return a >> 31; - } - - /** - * returns 0xffffffff if a >= b and zero otherwise, where a and b are both non-negative. - */ - private static int gte(int a, int b) { - a -= b; - // a >= 0 iff a >= b. - return ~(a >> 31); - } - } - - // (x = 0, y = 1) point - private static final CachedXYT CACHED_NEUTRAL = new CachedXYT( - new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); - private static final PartialXYZT NEUTRAL = new PartialXYZT( - new XYZ(new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}), - new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}); - - /** - * Projective point representation (X:Y:Z) satisfying x = X/Z, y = Y/Z - *

- * Note that this is referred as ge_p2 in ref10 impl. - * Also note that x = X, y = Y and z = Z below following Java coding style. - *

- * See - * Koyama K., Tsuruoka Y. (1993) Speeding up Elliptic Cryptosystems by Using a Signed Binary - * Window Method. - *

- * https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - */ - private static class XYZ { - - final long[] x; - final long[] y; - final long[] z; - - XYZ() { - this(new long[Field25519.LIMB_CNT], new long[Field25519.LIMB_CNT], new long[Field25519.LIMB_CNT]); - } - - XYZ(long[] x, long[] y, long[] z) { - this.x = x; - this.y = y; - this.z = z; - } - - XYZ(XYZ xyz) { - x = Arrays.copyOf(xyz.x, Field25519.LIMB_CNT); - y = Arrays.copyOf(xyz.y, Field25519.LIMB_CNT); - z = Arrays.copyOf(xyz.z, Field25519.LIMB_CNT); - } - - XYZ(PartialXYZT partialXYZT) { - this(); - fromPartialXYZT(this, partialXYZT); - } - - /** - * ge_p1p1_to_p2.c - */ - static XYZ fromPartialXYZT(XYZ out, PartialXYZT in) { - Field25519.mult(out.x, in.xyz.x, in.t); - Field25519.mult(out.y, in.xyz.y, in.xyz.z); - Field25519.mult(out.z, in.xyz.z, in.t); - return out; - } - - /** - * Encodes this point to bytes. - */ - byte[] toBytes() { - long[] recip = new long[Field25519.LIMB_CNT]; - long[] x = new long[Field25519.LIMB_CNT]; - long[] y = new long[Field25519.LIMB_CNT]; - Field25519.inverse(recip, z); - Field25519.mult(x, this.x, recip); - Field25519.mult(y, this.y, recip); - byte[] s = Field25519.contract(y); - s[31] = (byte) (s[31] ^ (getLsb(x) << 7)); - return s; - } - - - /** - * Best effort fix-timing array comparison. - * - * @return true if two arrays are equal. - */ - private static boolean bytesEqual(final byte[] x, final byte[] y) { - if (x == null || y == null) { - return false; - } - if (x.length != y.length) { - return false; - } - int res = 0; - for (int i = 0; i < x.length; i++) { - res |= x[i] ^ y[i]; - } - return res == 0; - } - - /** - * Checks that the point is on curve - */ - boolean isOnCurve() { - long[] x2 = new long[Field25519.LIMB_CNT]; - Field25519.square(x2, x); - long[] y2 = new long[Field25519.LIMB_CNT]; - Field25519.square(y2, y); - long[] z2 = new long[Field25519.LIMB_CNT]; - Field25519.square(z2, z); - long[] z4 = new long[Field25519.LIMB_CNT]; - Field25519.square(z4, z2); - long[] lhs = new long[Field25519.LIMB_CNT]; - // lhs = y^2 - x^2 - Field25519.sub(lhs, y2, x2); - // lhs = z^2 * (y2 - x2) - Field25519.mult(lhs, lhs, z2); - long[] rhs = new long[Field25519.LIMB_CNT]; - // rhs = x^2 * y^2 - Field25519.mult(rhs, x2, y2); - // rhs = D * x^2 * y^2 - Field25519.mult(rhs, rhs, D); - // rhs = z^4 + D * x^2 * y^2 - Field25519.sum(rhs, z4); - // Field25519.mult reduces its output, but Field25519.sum does not, so we have to manually - // reduce it here. - Field25519.reduce(rhs, rhs); - // z^2 (y^2 - x^2) == z^4 + D * x^2 * y^2 - return bytesEqual(Field25519.contract(lhs), Field25519.contract(rhs)); - } - } - - /** - * Represents extended projective point representation (X:Y:Z:T) satisfying x = X/Z, y = Y/Z, - * XY = ZT - *

- * Note that this is referred as ge_p3 in ref10 impl. - * Also note that t = T below following Java coding style. - *

- * See - * Hisil H., Wong K.KH., Carter G., Dawson E. (2008) Twisted Edwards Curves Revisited. - *

- * https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html - */ - private static class XYZT { - - final XYZ xyz; - final long[] t; - - XYZT() { - this(new XYZ(), new long[Field25519.LIMB_CNT]); - } - - XYZT(XYZ xyz, long[] t) { - this.xyz = xyz; - this.t = t; - } - - XYZT(PartialXYZT partialXYZT) { - this(); - fromPartialXYZT(this, partialXYZT); - } - - /** - * ge_p1p1_to_p2.c - */ - private static XYZT fromPartialXYZT(XYZT out, PartialXYZT in) { - Field25519.mult(out.xyz.x, in.xyz.x, in.t); - Field25519.mult(out.xyz.y, in.xyz.y, in.xyz.z); - Field25519.mult(out.xyz.z, in.xyz.z, in.t); - Field25519.mult(out.t, in.xyz.x, in.xyz.y); - return out; - } - - /** - * Decodes {@code s} into an extented projective point. - * See Section 5.1.3 Decoding in https://tools.ietf.org/html/rfc8032#section-5.1.3 - */ - private static XYZT fromBytesNegateVarTime(byte[] s) throws GeneralSecurityException { - long[] x = new long[Field25519.LIMB_CNT]; - long[] y = Field25519.expand(s); - long[] z = new long[Field25519.LIMB_CNT]; - z[0] = 1; - long[] t = new long[Field25519.LIMB_CNT]; - long[] u = new long[Field25519.LIMB_CNT]; - long[] v = new long[Field25519.LIMB_CNT]; - long[] vxx = new long[Field25519.LIMB_CNT]; - long[] check = new long[Field25519.LIMB_CNT]; - Field25519.square(u, y); - Field25519.mult(v, u, D); - Field25519.sub(u, u, z); // u = y^2 - 1 - Field25519.sum(v, v, z); // v = dy^2 + 1 - - long[] v3 = new long[Field25519.LIMB_CNT]; - Field25519.square(v3, v); - Field25519.mult(v3, v3, v); // v3 = v^3 - Field25519.square(x, v3); - Field25519.mult(x, x, v); - Field25519.mult(x, x, u); // x = uv^7 - - pow2252m3(x, x); // x = (uv^7)^((q-5)/8) - Field25519.mult(x, x, v3); - Field25519.mult(x, x, u); // x = uv^3(uv^7)^((q-5)/8) - - Field25519.square(vxx, x); - Field25519.mult(vxx, vxx, v); - Field25519.sub(check, vxx, u); // vx^2-u - if (isNonZeroVarTime(check)) { - Field25519.sum(check, vxx, u); // vx^2+u - if (isNonZeroVarTime(check)) { - throw new GeneralSecurityException("Cannot convert given bytes to extended projective " - + "coordinates. No square root exists for modulo 2^255-19"); - } - Field25519.mult(x, x, SQRTM1); - } - - if (!isNonZeroVarTime(x) && (s[31] & 0xff) >> 7 != 0) { - throw new GeneralSecurityException("Cannot convert given bytes to extended projective " - + "coordinates. Computed x is zero and encoded x's least significant bit is not zero"); - } - if (getLsb(x) == ((s[31] & 0xff) >> 7)) { - neg(x, x); - } - - Field25519.mult(t, x, y); - return new XYZT(new XYZ(x, y, z), t); - } - } - - /** - * Partial projective point representation ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T - *

- * Note that this is referred as complete form in the original ref10 impl (ge_p1p1). - * Also note that t = T below following Java coding style. - *

- * Although this has the same types as XYZT, it is redefined to have its own type so that it is - * readable and 1:1 corresponds to ref10 impl. - *

- * Can be converted to XYZT as follows: - * X1 = X * T = x * Z * T = x * Z1 - * Y1 = Y * Z = y * T * Z = y * Z1 - * Z1 = Z * T = Z * T - * T1 = X * Y = x * Z * y * T = x * y * Z1 = X1Y1 / Z1 - */ - private static class PartialXYZT { - - final XYZ xyz; - final long[] t; - - PartialXYZT() { - this(new XYZ(), new long[Field25519.LIMB_CNT]); - } - - PartialXYZT(XYZ xyz, long[] t) { - this.xyz = xyz; - this.t = t; - } - - PartialXYZT(PartialXYZT other) { - xyz = new XYZ(other.xyz); - t = Arrays.copyOf(other.t, Field25519.LIMB_CNT); - } - } - - /** - * Corresponds to the caching mentioned in the last paragraph of Section 3.1 of - * Hisil H., Wong K.KH., Carter G., Dawson E. (2008) Twisted Edwards Curves Revisited. - * with Z = 1. - */ - private static class CachedXYT { - - final long[] yPlusX; - final long[] yMinusX; - final long[] t2d; - - /** - * Creates a cached XYZT with Z = 1 - * - * @param yPlusX y + x - * @param yMinusX y - x - * @param t2d 2d * xy - */ - CachedXYT(long[] yPlusX, long[] yMinusX, long[] t2d) { - this.yPlusX = yPlusX; - this.yMinusX = yMinusX; - this.t2d = t2d; - } - - CachedXYT(CachedXYT other) { - yPlusX = Arrays.copyOf(other.yPlusX, Field25519.LIMB_CNT); - yMinusX = Arrays.copyOf(other.yMinusX, Field25519.LIMB_CNT); - t2d = Arrays.copyOf(other.t2d, Field25519.LIMB_CNT); - } - - // z is one implicitly, so this just copies {@code in} to {@code output}. - void multByZ(long[] output, long[] in) { - System.arraycopy(in, 0, output, 0, Field25519.LIMB_CNT); - } - - /** - * If icopy is 1, copies {@code other} into this point. Time invariant wrt to icopy value. - */ - void copyConditional(CachedXYT other, int icopy) { - copyConditional(yPlusX, other.yPlusX, icopy); - copyConditional(yMinusX, other.yMinusX, icopy); - copyConditional(t2d, other.t2d, icopy); - } - - /** - * Conditionally copies a reduced-form limb arrays {@code b} into {@code a} if {@code icopy} is 1, - * but leave {@code a} unchanged if 'iswap' is 0. Runs in data-invariant time to avoid - * side-channel attacks. - * - *

NOTE that this function requires that {@code icopy} be 1 or 0; other values give wrong - * results. Also, the two limb arrays must be in reduced-coefficient, reduced-degree form: the - * values in a[10..19] or b[10..19] aren't swapped, and all all values in a[0..9],b[0..9] must - * have magnitude less than Integer.MAX_VALUE. - */ - static void copyConditional(long[] a, long[] b, int icopy) { - int copy = -icopy; - for (int i = 0; i < Field25519.LIMB_CNT; i++) { - int x = copy & (((int) a[i]) ^ ((int) b[i])); - a[i] = ((int) a[i]) ^ x; - } - } - } - - private static class CachedXYZT extends CachedXYT { - - private final long[] z; - - CachedXYZT() { - this(new long[Field25519.LIMB_CNT], new long[Field25519.LIMB_CNT], new long[Field25519.LIMB_CNT], new long[Field25519.LIMB_CNT]); - } - - /** - * ge_p3_to_cached.c - */ - CachedXYZT(XYZT xyzt) { - this(); - Field25519.sum(yPlusX, xyzt.xyz.y, xyzt.xyz.x); - Field25519.sub(yMinusX, xyzt.xyz.y, xyzt.xyz.x); - System.arraycopy(xyzt.xyz.z, 0, z, 0, Field25519.LIMB_CNT); - Field25519.mult(t2d, xyzt.t, D2); - } - - /** - * Creates a cached XYZT - * - * @param yPlusX Y + X - * @param yMinusX Y - X - * @param z Z - * @param t2d 2d * (XY/Z) - */ - CachedXYZT(long[] yPlusX, long[] yMinusX, long[] z, long[] t2d) { - super(yPlusX, yMinusX, t2d); - this.z = z; - } - - @Override - public void multByZ(long[] output, long[] in) { - Field25519.mult(output, in, z); - } - } - - /** - * Addition defined in Section 3.1 of - * Hisil H., Wong K.KH., Carter G., Dawson E. (2008) Twisted Edwards Curves Revisited. - *

- * Please note that this is a partial of the operation listed there leaving out the final - * conversion from PartialXYZT to XYZT. - * - * @param extended extended projective point input - * @param cached cached projective point input - */ - private static void add(PartialXYZT partialXYZT, XYZT extended, CachedXYT cached) { - long[] t = new long[Field25519.LIMB_CNT]; - - // Y1 + X1 - Field25519.sum(partialXYZT.xyz.x, extended.xyz.y, extended.xyz.x); - - // Y1 - X1 - Field25519.sub(partialXYZT.xyz.y, extended.xyz.y, extended.xyz.x); - - // A = (Y1 - X1) * (Y2 - X2) - Field25519.mult(partialXYZT.xyz.y, partialXYZT.xyz.y, cached.yMinusX); - - // B = (Y1 + X1) * (Y2 + X2) - Field25519.mult(partialXYZT.xyz.z, partialXYZT.xyz.x, cached.yPlusX); - - // C = T1 * 2d * T2 = 2d * T1 * T2 (2d is written as k in the paper) - Field25519.mult(partialXYZT.t, extended.t, cached.t2d); - - // Z1 * Z2 - cached.multByZ(partialXYZT.xyz.x, extended.xyz.z); - - // D = 2 * Z1 * Z2 - Field25519.sum(t, partialXYZT.xyz.x, partialXYZT.xyz.x); - - // X3 = B - A - Field25519.sub(partialXYZT.xyz.x, partialXYZT.xyz.z, partialXYZT.xyz.y); - - // Y3 = B + A - Field25519.sum(partialXYZT.xyz.y, partialXYZT.xyz.z, partialXYZT.xyz.y); - - // Z3 = D + C - Field25519.sum(partialXYZT.xyz.z, t, partialXYZT.t); - - // T3 = D - C - Field25519.sub(partialXYZT.t, t, partialXYZT.t); - } - - /** - * Based on the addition defined in Section 3.1 of - * Hisil H., Wong K.KH., Carter G., Dawson E. (2008) Twisted Edwards Curves Revisited. - *

- * Please note that this is a partial of the operation listed there leaving out the final - * conversion from PartialXYZT to XYZT. - * - * @param extended extended projective point input - * @param cached cached projective point input - */ - private static void sub(PartialXYZT partialXYZT, XYZT extended, CachedXYT cached) { - long[] t = new long[Field25519.LIMB_CNT]; - - // Y1 + X1 - Field25519.sum(partialXYZT.xyz.x, extended.xyz.y, extended.xyz.x); - - // Y1 - X1 - Field25519.sub(partialXYZT.xyz.y, extended.xyz.y, extended.xyz.x); - - // A = (Y1 - X1) * (Y2 + X2) - Field25519.mult(partialXYZT.xyz.y, partialXYZT.xyz.y, cached.yPlusX); - - // B = (Y1 + X1) * (Y2 - X2) - Field25519.mult(partialXYZT.xyz.z, partialXYZT.xyz.x, cached.yMinusX); - - // C = T1 * 2d * T2 = 2d * T1 * T2 (2d is written as k in the paper) - Field25519.mult(partialXYZT.t, extended.t, cached.t2d); - - // Z1 * Z2 - cached.multByZ(partialXYZT.xyz.x, extended.xyz.z); - - // D = 2 * Z1 * Z2 - Field25519.sum(t, partialXYZT.xyz.x, partialXYZT.xyz.x); - - // X3 = B - A - Field25519.sub(partialXYZT.xyz.x, partialXYZT.xyz.z, partialXYZT.xyz.y); - - // Y3 = B + A - Field25519.sum(partialXYZT.xyz.y, partialXYZT.xyz.z, partialXYZT.xyz.y); - - // Z3 = D - C - Field25519.sub(partialXYZT.xyz.z, t, partialXYZT.t); - - // T3 = D + C - Field25519.sum(partialXYZT.t, t, partialXYZT.t); - } - - /** - * Doubles {@code p} and puts the result into this PartialXYZT. - *

- * This is based on the addition defined in formula 7 in Section 3.3 of - * Hisil H., Wong K.KH., Carter G., Dawson E. (2008) Twisted Edwards Curves Revisited. - *

- * Please note that this is a partial of the operation listed there leaving out the final - * conversion from PartialXYZT to XYZT and also this fixes a typo in calculation of Y3 and T3 in - * the paper, H should be replaced with A+B. - */ - private static void doubleXYZ(PartialXYZT partialXYZT, XYZ p) { - long[] t0 = new long[Field25519.LIMB_CNT]; - - // XX = X1^2 - Field25519.square(partialXYZT.xyz.x, p.x); - - // YY = Y1^2 - Field25519.square(partialXYZT.xyz.z, p.y); - - // B' = Z1^2 - Field25519.square(partialXYZT.t, p.z); - - // B = 2 * B' - Field25519.sum(partialXYZT.t, partialXYZT.t, partialXYZT.t); - - // A = X1 + Y1 - Field25519.sum(partialXYZT.xyz.y, p.x, p.y); - - // AA = A^2 - Field25519.square(t0, partialXYZT.xyz.y); - - // Y3 = YY + XX - Field25519.sum(partialXYZT.xyz.y, partialXYZT.xyz.z, partialXYZT.xyz.x); - - // Z3 = YY - XX - Field25519.sub(partialXYZT.xyz.z, partialXYZT.xyz.z, partialXYZT.xyz.x); - - // X3 = AA - Y3 - Field25519.sub(partialXYZT.xyz.x, t0, partialXYZT.xyz.y); - - // T3 = B - Z3 - Field25519.sub(partialXYZT.t, partialXYZT.t, partialXYZT.xyz.z); - } - - /** - * Doubles {@code p} and puts the result into this PartialXYZT. - */ - private static void doubleXYZT(PartialXYZT partialXYZT, XYZT p) { - doubleXYZ(partialXYZT, p.xyz); - } - - /** - * Compares two byte values in constant time. - */ - private static int eq(int a, int b) { - int r = ~(a ^ b) & 0xff; - r &= r << 4; - r &= r << 2; - r &= r << 1; - return (r >> 7) & 1; - } - - /** - * This is a constant time operation where point b*B*256^pos is stored in {@code t}. - * When b is 0, t remains the same (i.e., neutral point). - *

- * Although B_TABLE[32][8] (B_TABLE[i][j] = (j+1)*B*256^i) has j values in [0, 7], the select - * method negates the corresponding point if b is negative (which is straight forward in elliptic - * curves by just negating y coordinate). Therefore we can get multiples of B with the half of - * memory requirements. - * - * @param t neutral element (i.e., point 0), also serves as output. - * @param pos in B[pos][j] = (j+1)*B*256^pos - * @param b value in [-8, 8] range. - */ - private static void select(CachedXYT t, int pos, byte b) { - int bnegative = (b & 0xff) >> 7; - int babs = b - (((-bnegative) & b) << 1); - - t.copyConditional(B_TABLE[pos][0], eq(babs, 1)); - t.copyConditional(B_TABLE[pos][1], eq(babs, 2)); - t.copyConditional(B_TABLE[pos][2], eq(babs, 3)); - t.copyConditional(B_TABLE[pos][3], eq(babs, 4)); - t.copyConditional(B_TABLE[pos][4], eq(babs, 5)); - t.copyConditional(B_TABLE[pos][5], eq(babs, 6)); - t.copyConditional(B_TABLE[pos][6], eq(babs, 7)); - t.copyConditional(B_TABLE[pos][7], eq(babs, 8)); - - long[] yPlusX = Arrays.copyOf(t.yMinusX, Field25519.LIMB_CNT); - long[] yMinusX = Arrays.copyOf(t.yPlusX, Field25519.LIMB_CNT); - long[] t2d = Arrays.copyOf(t.t2d, Field25519.LIMB_CNT); - neg(t2d, t2d); - CachedXYT minust = new CachedXYT(yPlusX, yMinusX, t2d); - t.copyConditional(minust, bnegative); - } - - /** - * Computes {@code a}*B - * where a = a[0]+256*a[1]+...+256^31 a[31] and - * B is the Ed25519 base point (x,4/5) with x positive. - *

- * Preconditions: - * a[31] <= 127 - * - * @throws IllegalStateException iff there is arithmetic error. - */ - @SuppressWarnings("NarrowingCompoundAssignment") - private static XYZ scalarMultWithBase(byte[] a) { - byte[] e = new byte[2 * Field25519.FIELD_LEN]; - for (int i = 0; i < Field25519.FIELD_LEN; i++) { - e[2 * i + 0] = (byte) (((a[i] & 0xff) >> 0) & 0xf); - e[2 * i + 1] = (byte) (((a[i] & 0xff) >> 4) & 0xf); - } - // each e[i] is between 0 and 15 - // e[63] is between 0 and 7 - - // Rewrite e in a way that each e[i] is in [-8, 8]. - // This can be done since a[63] is in [0, 7], the carry-over onto the most significant byte - // a[63] can be at most 1. - int carry = 0; - for (int i = 0; i < e.length - 1; i++) { - e[i] += carry; - carry = e[i] + 8; - carry >>= 4; - e[i] -= carry << 4; - } - e[e.length - 1] += carry; - - PartialXYZT ret = new PartialXYZT(NEUTRAL); - XYZT xyzt = new XYZT(); - // Although B_TABLE's i can be at most 31 (stores only 32 4bit multiples of B) and we have 64 - // 4bit values in e array, the below for loop adds cached values by iterating e by two in odd - // indices. After the result, we can double the result point 4 times to shift the multiplication - // scalar by 4 bits. - for (int i = 1; i < e.length; i += 2) { - CachedXYT t = new CachedXYT(CACHED_NEUTRAL); - select(t, i / 2, e[i]); - add(ret, XYZT.fromPartialXYZT(xyzt, ret), t); - } - - // Doubles the result 4 times to shift the multiplication scalar 4 bits to get the actual result - // for the odd indices in e. - XYZ xyz = new XYZ(); - doubleXYZ(ret, XYZ.fromPartialXYZT(xyz, ret)); - doubleXYZ(ret, XYZ.fromPartialXYZT(xyz, ret)); - doubleXYZ(ret, XYZ.fromPartialXYZT(xyz, ret)); - doubleXYZ(ret, XYZ.fromPartialXYZT(xyz, ret)); - - // Add multiples of B for even indices of e. - for (int i = 0; i < e.length; i += 2) { - CachedXYT t = new CachedXYT(CACHED_NEUTRAL); - select(t, i / 2, e[i]); - add(ret, XYZT.fromPartialXYZT(xyzt, ret), t); - } - - // This check is to protect against flaws, i.e. if there is a computation error through a - // faulty CPU or if the implementation contains a bug. - XYZ result = new XYZ(ret); - if (!result.isOnCurve()) { - throw new IllegalStateException("arithmetic error in scalar multiplication"); - } - return result; - } - - @SuppressWarnings("NarrowingCompoundAssignment") - private static byte[] slide(byte[] a) { - byte[] r = new byte[256]; - // Writes each bit in a[0..31] into r[0..255]: - // a = a[0]+256*a[1]+...+256^31*a[31] is equal to - // r = r[0]+2*r[1]+...+2^255*r[255] - for (int i = 0; i < 256; i++) { - r[i] = (byte) (1 & ((a[i >> 3] & 0xff) >> (i & 7))); - } - - // Transforms r[i] as odd values in [-15, 15] - for (int i = 0; i < 256; i++) { - if (r[i] != 0) { - for (int b = 1; b <= 6 && i + b < 256; b++) { - if (r[i + b] != 0) { - if (r[i] + (r[i + b] << b) <= 15) { - r[i] += r[i + b] << b; - r[i + b] = 0; - } else if (r[i] - (r[i + b] << b) >= -15) { - r[i] -= r[i + b] << b; - for (int k = i + b; k < 256; k++) { - if (r[k] == 0) { - r[k] = 1; - break; - } - r[k] = 0; - } - } else { - break; - } - } - } - } - } - return r; - } - - /** - * Computes {@code a}*{@code pointA}+{@code b}*B - * where a = a[0]+256*a[1]+...+256^31*a[31]. - * and b = b[0]+256*b[1]+...+256^31*b[31]. - * B is the Ed25519 base point (x,4/5) with x positive. - *

- * Note that execution time varies based on the input since this will only be used in verification - * of signatures. - */ - private static XYZ doubleScalarMultVarTime(byte[] a, XYZT pointA, byte[] b) { - // pointA, 3*pointA, 5*pointA, 7*pointA, 9*pointA, 11*pointA, 13*pointA, 15*pointA - CachedXYZT[] pointAArray = new CachedXYZT[8]; - pointAArray[0] = new CachedXYZT(pointA); - PartialXYZT t = new PartialXYZT(); - doubleXYZT(t, pointA); - XYZT doubleA = new XYZT(t); - for (int i = 1; i < pointAArray.length; i++) { - add(t, doubleA, pointAArray[i - 1]); - pointAArray[i] = new CachedXYZT(new XYZT(t)); - } - - byte[] aSlide = slide(a); - byte[] bSlide = slide(b); - t = new PartialXYZT(NEUTRAL); - XYZT u = new XYZT(); - int i = 255; - for (; i >= 0; i--) { - if (aSlide[i] != 0 || bSlide[i] != 0) { - break; - } - } - for (; i >= 0; i--) { - doubleXYZ(t, new XYZ(t)); - if (aSlide[i] > 0) { - add(t, XYZT.fromPartialXYZT(u, t), pointAArray[aSlide[i] / 2]); - } else if (aSlide[i] < 0) { - sub(t, XYZT.fromPartialXYZT(u, t), pointAArray[-aSlide[i] / 2]); - } - if (bSlide[i] > 0) { - add(t, XYZT.fromPartialXYZT(u, t), B2[bSlide[i] / 2]); - } else if (bSlide[i] < 0) { - sub(t, XYZT.fromPartialXYZT(u, t), B2[-bSlide[i] / 2]); - } - } - - return new XYZ(t); - } - - /** - * Returns true if {@code in} is nonzero. - *

- * Note that execution time might depend on the input {@code in}. - */ - private static boolean isNonZeroVarTime(long[] in) { - long[] inCopy = new long[in.length + 1]; - System.arraycopy(in, 0, inCopy, 0, in.length); - Field25519.reduceCoefficients(inCopy); - byte[] bytes = Field25519.contract(inCopy); - for (byte b : bytes) { - if (b != 0) { - return true; - } - } - return false; - } - - /** - * Returns the least significant bit of {@code in}. - */ - private static int getLsb(long[] in) { - return Field25519.contract(in)[0] & 1; - } - - /** - * Negates all values in {@code in} and store it in {@code out}. - */ - private static void neg(long[] out, long[] in) { - for (int i = 0; i < in.length; i++) { - out[i] = -in[i]; - } - } - - /** - * Computes {@code in}^(2^252-3) mod 2^255-19 and puts the result in {@code out}. - */ - private static void pow2252m3(long[] out, long[] in) { - long[] t0 = new long[Field25519.LIMB_CNT]; - long[] t1 = new long[Field25519.LIMB_CNT]; - long[] t2 = new long[Field25519.LIMB_CNT]; - - // z2 = z1^2^1 - Field25519.square(t0, in); - - // z8 = z2^2^2 - Field25519.square(t1, t0); - for (int i = 1; i < 2; i++) { - Field25519.square(t1, t1); - } - - // z9 = z1*z8 - Field25519.mult(t1, in, t1); - - // z11 = z2*z9 - Field25519.mult(t0, t0, t1); - - // z22 = z11^2^1 - Field25519.square(t0, t0); - - // z_5_0 = z9*z22 - Field25519.mult(t0, t1, t0); - - // z_10_5 = z_5_0^2^5 - Field25519.square(t1, t0); - for (int i = 1; i < 5; i++) { - Field25519.square(t1, t1); - } - - // z_10_0 = z_10_5*z_5_0 - Field25519.mult(t0, t1, t0); - - // z_20_10 = z_10_0^2^10 - Field25519.square(t1, t0); - for (int i = 1; i < 10; i++) { - Field25519.square(t1, t1); - } - - // z_20_0 = z_20_10*z_10_0 - Field25519.mult(t1, t1, t0); - - // z_40_20 = z_20_0^2^20 - Field25519.square(t2, t1); - for (int i = 1; i < 20; i++) { - Field25519.square(t2, t2); - } - - // z_40_0 = z_40_20*z_20_0 - Field25519.mult(t1, t2, t1); - - // z_50_10 = z_40_0^2^10 - Field25519.square(t1, t1); - for (int i = 1; i < 10; i++) { - Field25519.square(t1, t1); - } - - // z_50_0 = z_50_10*z_10_0 - Field25519.mult(t0, t1, t0); - - // z_100_50 = z_50_0^2^50 - Field25519.square(t1, t0); - for (int i = 1; i < 50; i++) { - Field25519.square(t1, t1); - } - - // z_100_0 = z_100_50*z_50_0 - Field25519.mult(t1, t1, t0); - - // z_200_100 = z_100_0^2^100 - Field25519.square(t2, t1); - for (int i = 1; i < 100; i++) { - Field25519.square(t2, t2); - } - - // z_200_0 = z_200_100*z_100_0 - Field25519.mult(t1, t2, t1); - - // z_250_50 = z_200_0^2^50 - Field25519.square(t1, t1); - for (int i = 1; i < 50; i++) { - Field25519.square(t1, t1); - } - - // z_250_0 = z_250_50*z_50_0 - Field25519.mult(t0, t1, t0); - - // z_252_2 = z_250_0^2^2 - Field25519.square(t0, t0); - for (int i = 1; i < 2; i++) { - Field25519.square(t0, t0); - } - - // z_252_3 = z_252_2*z1 - Field25519.mult(out, t0, in); - } - - /** - * Returns 3 bytes of {@code in} starting from {@code idx} in Little-Endian format. - */ - private static long load3(byte[] in, int idx) { - long result; - result = (long) in[idx] & 0xff; - result |= (long) (in[idx + 1] & 0xff) << 8; - result |= (long) (in[idx + 2] & 0xff) << 16; - return result; - } - - /** - * Returns 4 bytes of {@code in} starting from {@code idx} in Little-Endian format. - */ - private static long load4(byte[] in, int idx) { - long result = load3(in, idx); - result |= (long) (in[idx + 3] & 0xff) << 24; - return result; - } - - /** - * Input: - * s[0]+256*s[1]+...+256^63*s[63] = s - *

- * Output: - * s[0]+256*s[1]+...+256^31*s[31] = s mod l - * where l = 2^252 + 27742317777372353535851937790883648493. - * Overwrites s in place. - */ - private static void reduce(byte[] s) { - // Observation: - // 2^252 mod l is equivalent to -27742317777372353535851937790883648493 mod l - // Let m = -27742317777372353535851937790883648493 - // Thus a*2^252+b mod l is equivalent to a*m+b mod l - // - // First s is divided into chunks of 21 bits as follows: - // s0+2^21*s1+2^42*s3+...+2^462*s23 = s[0]+256*s[1]+...+256^63*s[63] - long s0 = 2097151 & load3(s, 0); - long s1 = 2097151 & (load4(s, 2) >> 5); - long s2 = 2097151 & (load3(s, 5) >> 2); - long s3 = 2097151 & (load4(s, 7) >> 7); - long s4 = 2097151 & (load4(s, 10) >> 4); - long s5 = 2097151 & (load3(s, 13) >> 1); - long s6 = 2097151 & (load4(s, 15) >> 6); - long s7 = 2097151 & (load3(s, 18) >> 3); - long s8 = 2097151 & load3(s, 21); - long s9 = 2097151 & (load4(s, 23) >> 5); - long s10 = 2097151 & (load3(s, 26) >> 2); - long s11 = 2097151 & (load4(s, 28) >> 7); - long s12 = 2097151 & (load4(s, 31) >> 4); - long s13 = 2097151 & (load3(s, 34) >> 1); - long s14 = 2097151 & (load4(s, 36) >> 6); - long s15 = 2097151 & (load3(s, 39) >> 3); - long s16 = 2097151 & load3(s, 42); - long s17 = 2097151 & (load4(s, 44) >> 5); - long s18 = 2097151 & (load3(s, 47) >> 2); - long s19 = 2097151 & (load4(s, 49) >> 7); - long s20 = 2097151 & (load4(s, 52) >> 4); - long s21 = 2097151 & (load3(s, 55) >> 1); - long s22 = 2097151 & (load4(s, 57) >> 6); - long s23 = (load4(s, 60) >> 3); - long carry0; - long carry1; - long carry2; - long carry3; - long carry4; - long carry5; - long carry6; - long carry7; - long carry8; - long carry9; - long carry10; - long carry11; - long carry12; - long carry13; - long carry14; - long carry15; - long carry16; - - // s23*2^462 = s23*2^210*2^252 is equivalent to s23*2^210*m in mod l - // As m is a 125 bit number, the result needs to scattered to 6 limbs (125/21 ceil is 6) - // starting from s11 (s11*2^210) - // m = [666643, 470296, 654183, -997805, 136657, -683901] in 21-bit limbs - s11 += s23 * 666643; - s12 += s23 * 470296; - s13 += s23 * 654183; - s14 -= s23 * 997805; - s15 += s23 * 136657; - s16 -= s23 * 683901; - // s23 = 0; - - s10 += s22 * 666643; - s11 += s22 * 470296; - s12 += s22 * 654183; - s13 -= s22 * 997805; - s14 += s22 * 136657; - s15 -= s22 * 683901; - // s22 = 0; - - s9 += s21 * 666643; - s10 += s21 * 470296; - s11 += s21 * 654183; - s12 -= s21 * 997805; - s13 += s21 * 136657; - s14 -= s21 * 683901; - // s21 = 0; - - s8 += s20 * 666643; - s9 += s20 * 470296; - s10 += s20 * 654183; - s11 -= s20 * 997805; - s12 += s20 * 136657; - s13 -= s20 * 683901; - // s20 = 0; - - s7 += s19 * 666643; - s8 += s19 * 470296; - s9 += s19 * 654183; - s10 -= s19 * 997805; - s11 += s19 * 136657; - s12 -= s19 * 683901; - // s19 = 0; - - s6 += s18 * 666643; - s7 += s18 * 470296; - s8 += s18 * 654183; - s9 -= s18 * 997805; - s10 += s18 * 136657; - s11 -= s18 * 683901; - // s18 = 0; - - // Reduce the bit length of limbs from s6 to s15 to 21-bits. - carry6 = (s6 + (1 << 20)) >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry8 = (s8 + (1 << 20)) >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry10 = (s10 + (1 << 20)) >> 21; - s11 += carry10; - s10 -= carry10 << 21; - carry12 = (s12 + (1 << 20)) >> 21; - s13 += carry12; - s12 -= carry12 << 21; - carry14 = (s14 + (1 << 20)) >> 21; - s15 += carry14; - s14 -= carry14 << 21; - carry16 = (s16 + (1 << 20)) >> 21; - s17 += carry16; - s16 -= carry16 << 21; - - carry7 = (s7 + (1 << 20)) >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry9 = (s9 + (1 << 20)) >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry11 = (s11 + (1 << 20)) >> 21; - s12 += carry11; - s11 -= carry11 << 21; - carry13 = (s13 + (1 << 20)) >> 21; - s14 += carry13; - s13 -= carry13 << 21; - carry15 = (s15 + (1 << 20)) >> 21; - s16 += carry15; - s15 -= carry15 << 21; - - // Resume reduction where we left off. - s5 += s17 * 666643; - s6 += s17 * 470296; - s7 += s17 * 654183; - s8 -= s17 * 997805; - s9 += s17 * 136657; - s10 -= s17 * 683901; - // s17 = 0; - - s4 += s16 * 666643; - s5 += s16 * 470296; - s6 += s16 * 654183; - s7 -= s16 * 997805; - s8 += s16 * 136657; - s9 -= s16 * 683901; - // s16 = 0; - - s3 += s15 * 666643; - s4 += s15 * 470296; - s5 += s15 * 654183; - s6 -= s15 * 997805; - s7 += s15 * 136657; - s8 -= s15 * 683901; - // s15 = 0; - - s2 += s14 * 666643; - s3 += s14 * 470296; - s4 += s14 * 654183; - s5 -= s14 * 997805; - s6 += s14 * 136657; - s7 -= s14 * 683901; - // s14 = 0; - - s1 += s13 * 666643; - s2 += s13 * 470296; - s3 += s13 * 654183; - s4 -= s13 * 997805; - s5 += s13 * 136657; - s6 -= s13 * 683901; - // s13 = 0; - - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - s12 = 0; - - // Reduce the range of limbs from s0 to s11 to 21-bits. - carry0 = (s0 + (1 << 20)) >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry2 = (s2 + (1 << 20)) >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry4 = (s4 + (1 << 20)) >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry6 = (s6 + (1 << 20)) >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry8 = (s8 + (1 << 20)) >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry10 = (s10 + (1 << 20)) >> 21; - s11 += carry10; - s10 -= carry10 << 21; - - carry1 = (s1 + (1 << 20)) >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry3 = (s3 + (1 << 20)) >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry5 = (s5 + (1 << 20)) >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry7 = (s7 + (1 << 20)) >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry9 = (s9 + (1 << 20)) >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry11 = (s11 + (1 << 20)) >> 21; - s12 += carry11; - s11 -= carry11 << 21; - - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - s12 = 0; - - // Carry chain reduction to propagate excess bits from s0 to s5 to the most significant limbs. - carry0 = s0 >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry1 = s1 >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry2 = s2 >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry3 = s3 >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry4 = s4 >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry5 = s5 >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry6 = s6 >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry7 = s7 >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry8 = s8 >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry9 = s9 >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry10 = s10 >> 21; - s11 += carry10; - s10 -= carry10 << 21; - carry11 = s11 >> 21; - s12 += carry11; - s11 -= carry11 << 21; - - // Do one last reduction as s12 might be 1. - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - // s12 = 0; - - carry0 = s0 >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry1 = s1 >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry2 = s2 >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry3 = s3 >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry4 = s4 >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry5 = s5 >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry6 = s6 >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry7 = s7 >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry8 = s8 >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry9 = s9 >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry10 = s10 >> 21; - s11 += carry10; - s10 -= carry10 << 21; - - // Serialize the result into the s. - s[0] = (byte) s0; - s[1] = (byte) (s0 >> 8); - s[2] = (byte) ((s0 >> 16) | (s1 << 5)); - s[3] = (byte) (s1 >> 3); - s[4] = (byte) (s1 >> 11); - s[5] = (byte) ((s1 >> 19) | (s2 << 2)); - s[6] = (byte) (s2 >> 6); - s[7] = (byte) ((s2 >> 14) | (s3 << 7)); - s[8] = (byte) (s3 >> 1); - s[9] = (byte) (s3 >> 9); - s[10] = (byte) ((s3 >> 17) | (s4 << 4)); - s[11] = (byte) (s4 >> 4); - s[12] = (byte) (s4 >> 12); - s[13] = (byte) ((s4 >> 20) | (s5 << 1)); - s[14] = (byte) (s5 >> 7); - s[15] = (byte) ((s5 >> 15) | (s6 << 6)); - s[16] = (byte) (s6 >> 2); - s[17] = (byte) (s6 >> 10); - s[18] = (byte) ((s6 >> 18) | (s7 << 3)); - s[19] = (byte) (s7 >> 5); - s[20] = (byte) (s7 >> 13); - s[21] = (byte) s8; - s[22] = (byte) (s8 >> 8); - s[23] = (byte) ((s8 >> 16) | (s9 << 5)); - s[24] = (byte) (s9 >> 3); - s[25] = (byte) (s9 >> 11); - s[26] = (byte) ((s9 >> 19) | (s10 << 2)); - s[27] = (byte) (s10 >> 6); - s[28] = (byte) ((s10 >> 14) | (s11 << 7)); - s[29] = (byte) (s11 >> 1); - s[30] = (byte) (s11 >> 9); - s[31] = (byte) (s11 >> 17); - } - - /** - * Input: - * a[0]+256*a[1]+...+256^31*a[31] = a - * b[0]+256*b[1]+...+256^31*b[31] = b - * c[0]+256*c[1]+...+256^31*c[31] = c - *

- * Output: - * s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l - * where l = 2^252 + 27742317777372353535851937790883648493. - */ - private static void mulAdd(byte[] s, byte[] a, byte[] b, byte[] c) { - // This is very similar to Ed25519.reduce, the difference in here is that it computes ab+c - // See Ed25519.reduce for related comments. - long a0 = 2097151 & load3(a, 0); - long a1 = 2097151 & (load4(a, 2) >> 5); - long a2 = 2097151 & (load3(a, 5) >> 2); - long a3 = 2097151 & (load4(a, 7) >> 7); - long a4 = 2097151 & (load4(a, 10) >> 4); - long a5 = 2097151 & (load3(a, 13) >> 1); - long a6 = 2097151 & (load4(a, 15) >> 6); - long a7 = 2097151 & (load3(a, 18) >> 3); - long a8 = 2097151 & load3(a, 21); - long a9 = 2097151 & (load4(a, 23) >> 5); - long a10 = 2097151 & (load3(a, 26) >> 2); - long a11 = (load4(a, 28) >> 7); - long b0 = 2097151 & load3(b, 0); - long b1 = 2097151 & (load4(b, 2) >> 5); - long b2 = 2097151 & (load3(b, 5) >> 2); - long b3 = 2097151 & (load4(b, 7) >> 7); - long b4 = 2097151 & (load4(b, 10) >> 4); - long b5 = 2097151 & (load3(b, 13) >> 1); - long b6 = 2097151 & (load4(b, 15) >> 6); - long b7 = 2097151 & (load3(b, 18) >> 3); - long b8 = 2097151 & load3(b, 21); - long b9 = 2097151 & (load4(b, 23) >> 5); - long b10 = 2097151 & (load3(b, 26) >> 2); - long b11 = (load4(b, 28) >> 7); - long c0 = 2097151 & load3(c, 0); - long c1 = 2097151 & (load4(c, 2) >> 5); - long c2 = 2097151 & (load3(c, 5) >> 2); - long c3 = 2097151 & (load4(c, 7) >> 7); - long c4 = 2097151 & (load4(c, 10) >> 4); - long c5 = 2097151 & (load3(c, 13) >> 1); - long c6 = 2097151 & (load4(c, 15) >> 6); - long c7 = 2097151 & (load3(c, 18) >> 3); - long c8 = 2097151 & load3(c, 21); - long c9 = 2097151 & (load4(c, 23) >> 5); - long c10 = 2097151 & (load3(c, 26) >> 2); - long c11 = (load4(c, 28) >> 7); - long s0; - long s1; - long s2; - long s3; - long s4; - long s5; - long s6; - long s7; - long s8; - long s9; - long s10; - long s11; - long s12; - long s13; - long s14; - long s15; - long s16; - long s17; - long s18; - long s19; - long s20; - long s21; - long s22; - long s23; - long carry0; - long carry1; - long carry2; - long carry3; - long carry4; - long carry5; - long carry6; - long carry7; - long carry8; - long carry9; - long carry10; - long carry11; - long carry12; - long carry13; - long carry14; - long carry15; - long carry16; - long carry17; - long carry18; - long carry19; - long carry20; - long carry21; - long carry22; - - s0 = c0 + a0 * b0; - s1 = c1 + a0 * b1 + a1 * b0; - s2 = c2 + a0 * b2 + a1 * b1 + a2 * b0; - s3 = c3 + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0; - s4 = c4 + a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0; - s5 = c5 + a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0; - s6 = c6 + a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0; - s7 = c7 + a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 + a6 * b1 + a7 * b0; - s8 = c8 + a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 + a6 * b2 + a7 * b1 - + a8 * b0; - s9 = c9 + a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 + a6 * b3 + a7 * b2 - + a8 * b1 + a9 * b0; - s10 = c10 + a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 + a6 * b4 + a7 * b3 - + a8 * b2 + a9 * b1 + a10 * b0; - s11 = c11 + a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 + a6 * b5 + a7 * b4 - + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0; - s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 + a7 * b5 + a8 * b4 + a9 * b3 - + a10 * b2 + a11 * b1; - s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 + a8 * b5 + a9 * b4 + a10 * b3 - + a11 * b2; - s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 + a9 * b5 + a10 * b4 - + a11 * b3; - s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 + a10 * b5 + a11 * b4; - s16 = a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5; - s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6; - s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7; - s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8; - s20 = a9 * b11 + a10 * b10 + a11 * b9; - s21 = a10 * b11 + a11 * b10; - s22 = a11 * b11; - s23 = 0; - - carry0 = (s0 + (1 << 20)) >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry2 = (s2 + (1 << 20)) >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry4 = (s4 + (1 << 20)) >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry6 = (s6 + (1 << 20)) >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry8 = (s8 + (1 << 20)) >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry10 = (s10 + (1 << 20)) >> 21; - s11 += carry10; - s10 -= carry10 << 21; - carry12 = (s12 + (1 << 20)) >> 21; - s13 += carry12; - s12 -= carry12 << 21; - carry14 = (s14 + (1 << 20)) >> 21; - s15 += carry14; - s14 -= carry14 << 21; - carry16 = (s16 + (1 << 20)) >> 21; - s17 += carry16; - s16 -= carry16 << 21; - carry18 = (s18 + (1 << 20)) >> 21; - s19 += carry18; - s18 -= carry18 << 21; - carry20 = (s20 + (1 << 20)) >> 21; - s21 += carry20; - s20 -= carry20 << 21; - carry22 = (s22 + (1 << 20)) >> 21; - s23 += carry22; - s22 -= carry22 << 21; - - carry1 = (s1 + (1 << 20)) >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry3 = (s3 + (1 << 20)) >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry5 = (s5 + (1 << 20)) >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry7 = (s7 + (1 << 20)) >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry9 = (s9 + (1 << 20)) >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry11 = (s11 + (1 << 20)) >> 21; - s12 += carry11; - s11 -= carry11 << 21; - carry13 = (s13 + (1 << 20)) >> 21; - s14 += carry13; - s13 -= carry13 << 21; - carry15 = (s15 + (1 << 20)) >> 21; - s16 += carry15; - s15 -= carry15 << 21; - carry17 = (s17 + (1 << 20)) >> 21; - s18 += carry17; - s17 -= carry17 << 21; - carry19 = (s19 + (1 << 20)) >> 21; - s20 += carry19; - s19 -= carry19 << 21; - carry21 = (s21 + (1 << 20)) >> 21; - s22 += carry21; - s21 -= carry21 << 21; - - s11 += s23 * 666643; - s12 += s23 * 470296; - s13 += s23 * 654183; - s14 -= s23 * 997805; - s15 += s23 * 136657; - s16 -= s23 * 683901; - // s23 = 0; - - s10 += s22 * 666643; - s11 += s22 * 470296; - s12 += s22 * 654183; - s13 -= s22 * 997805; - s14 += s22 * 136657; - s15 -= s22 * 683901; - // s22 = 0; - - s9 += s21 * 666643; - s10 += s21 * 470296; - s11 += s21 * 654183; - s12 -= s21 * 997805; - s13 += s21 * 136657; - s14 -= s21 * 683901; - // s21 = 0; - - s8 += s20 * 666643; - s9 += s20 * 470296; - s10 += s20 * 654183; - s11 -= s20 * 997805; - s12 += s20 * 136657; - s13 -= s20 * 683901; - // s20 = 0; - - s7 += s19 * 666643; - s8 += s19 * 470296; - s9 += s19 * 654183; - s10 -= s19 * 997805; - s11 += s19 * 136657; - s12 -= s19 * 683901; - // s19 = 0; - - s6 += s18 * 666643; - s7 += s18 * 470296; - s8 += s18 * 654183; - s9 -= s18 * 997805; - s10 += s18 * 136657; - s11 -= s18 * 683901; - // s18 = 0; - - carry6 = (s6 + (1 << 20)) >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry8 = (s8 + (1 << 20)) >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry10 = (s10 + (1 << 20)) >> 21; - s11 += carry10; - s10 -= carry10 << 21; - carry12 = (s12 + (1 << 20)) >> 21; - s13 += carry12; - s12 -= carry12 << 21; - carry14 = (s14 + (1 << 20)) >> 21; - s15 += carry14; - s14 -= carry14 << 21; - carry16 = (s16 + (1 << 20)) >> 21; - s17 += carry16; - s16 -= carry16 << 21; - - carry7 = (s7 + (1 << 20)) >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry9 = (s9 + (1 << 20)) >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry11 = (s11 + (1 << 20)) >> 21; - s12 += carry11; - s11 -= carry11 << 21; - carry13 = (s13 + (1 << 20)) >> 21; - s14 += carry13; - s13 -= carry13 << 21; - carry15 = (s15 + (1 << 20)) >> 21; - s16 += carry15; - s15 -= carry15 << 21; - - s5 += s17 * 666643; - s6 += s17 * 470296; - s7 += s17 * 654183; - s8 -= s17 * 997805; - s9 += s17 * 136657; - s10 -= s17 * 683901; - // s17 = 0; - - s4 += s16 * 666643; - s5 += s16 * 470296; - s6 += s16 * 654183; - s7 -= s16 * 997805; - s8 += s16 * 136657; - s9 -= s16 * 683901; - // s16 = 0; - - s3 += s15 * 666643; - s4 += s15 * 470296; - s5 += s15 * 654183; - s6 -= s15 * 997805; - s7 += s15 * 136657; - s8 -= s15 * 683901; - // s15 = 0; - - s2 += s14 * 666643; - s3 += s14 * 470296; - s4 += s14 * 654183; - s5 -= s14 * 997805; - s6 += s14 * 136657; - s7 -= s14 * 683901; - // s14 = 0; - - s1 += s13 * 666643; - s2 += s13 * 470296; - s3 += s13 * 654183; - s4 -= s13 * 997805; - s5 += s13 * 136657; - s6 -= s13 * 683901; - // s13 = 0; - - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - s12 = 0; - - carry0 = (s0 + (1 << 20)) >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry2 = (s2 + (1 << 20)) >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry4 = (s4 + (1 << 20)) >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry6 = (s6 + (1 << 20)) >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry8 = (s8 + (1 << 20)) >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry10 = (s10 + (1 << 20)) >> 21; - s11 += carry10; - s10 -= carry10 << 21; - - carry1 = (s1 + (1 << 20)) >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry3 = (s3 + (1 << 20)) >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry5 = (s5 + (1 << 20)) >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry7 = (s7 + (1 << 20)) >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry9 = (s9 + (1 << 20)) >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry11 = (s11 + (1 << 20)) >> 21; - s12 += carry11; - s11 -= carry11 << 21; - - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - s12 = 0; - - carry0 = s0 >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry1 = s1 >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry2 = s2 >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry3 = s3 >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry4 = s4 >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry5 = s5 >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry6 = s6 >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry7 = s7 >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry8 = s8 >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry9 = s9 >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry10 = s10 >> 21; - s11 += carry10; - s10 -= carry10 << 21; - carry11 = s11 >> 21; - s12 += carry11; - s11 -= carry11 << 21; - - s0 += s12 * 666643; - s1 += s12 * 470296; - s2 += s12 * 654183; - s3 -= s12 * 997805; - s4 += s12 * 136657; - s5 -= s12 * 683901; - // s12 = 0; - - carry0 = s0 >> 21; - s1 += carry0; - s0 -= carry0 << 21; - carry1 = s1 >> 21; - s2 += carry1; - s1 -= carry1 << 21; - carry2 = s2 >> 21; - s3 += carry2; - s2 -= carry2 << 21; - carry3 = s3 >> 21; - s4 += carry3; - s3 -= carry3 << 21; - carry4 = s4 >> 21; - s5 += carry4; - s4 -= carry4 << 21; - carry5 = s5 >> 21; - s6 += carry5; - s5 -= carry5 << 21; - carry6 = s6 >> 21; - s7 += carry6; - s6 -= carry6 << 21; - carry7 = s7 >> 21; - s8 += carry7; - s7 -= carry7 << 21; - carry8 = s8 >> 21; - s9 += carry8; - s8 -= carry8 << 21; - carry9 = s9 >> 21; - s10 += carry9; - s9 -= carry9 << 21; - carry10 = s10 >> 21; - s11 += carry10; - s10 -= carry10 << 21; - - s[0] = (byte) s0; - s[1] = (byte) (s0 >> 8); - s[2] = (byte) ((s0 >> 16) | (s1 << 5)); - s[3] = (byte) (s1 >> 3); - s[4] = (byte) (s1 >> 11); - s[5] = (byte) ((s1 >> 19) | (s2 << 2)); - s[6] = (byte) (s2 >> 6); - s[7] = (byte) ((s2 >> 14) | (s3 << 7)); - s[8] = (byte) (s3 >> 1); - s[9] = (byte) (s3 >> 9); - s[10] = (byte) ((s3 >> 17) | (s4 << 4)); - s[11] = (byte) (s4 >> 4); - s[12] = (byte) (s4 >> 12); - s[13] = (byte) ((s4 >> 20) | (s5 << 1)); - s[14] = (byte) (s5 >> 7); - s[15] = (byte) ((s5 >> 15) | (s6 << 6)); - s[16] = (byte) (s6 >> 2); - s[17] = (byte) (s6 >> 10); - s[18] = (byte) ((s6 >> 18) | (s7 << 3)); - s[19] = (byte) (s7 >> 5); - s[20] = (byte) (s7 >> 13); - s[21] = (byte) s8; - s[22] = (byte) (s8 >> 8); - s[23] = (byte) ((s8 >> 16) | (s9 << 5)); - s[24] = (byte) (s9 >> 3); - s[25] = (byte) (s9 >> 11); - s[26] = (byte) ((s9 >> 19) | (s10 << 2)); - s[27] = (byte) (s10 >> 6); - s[28] = (byte) ((s10 >> 14) | (s11 << 7)); - s[29] = (byte) (s11 >> 1); - s[30] = (byte) (s11 >> 9); - s[31] = (byte) (s11 >> 17); - } - - // The order of the generator as unsigned bytes in little endian order. - // (2^252 + 0x14def9dea2f79cd65812631a5cf5d3ed, cf. RFC 7748) - private static final byte[] GROUP_ORDER = { - (byte) 0xed, (byte) 0xd3, (byte) 0xf5, (byte) 0x5c, - (byte) 0x1a, (byte) 0x63, (byte) 0x12, (byte) 0x58, - (byte) 0xd6, (byte) 0x9c, (byte) 0xf7, (byte) 0xa2, - (byte) 0xde, (byte) 0xf9, (byte) 0xde, (byte) 0x14, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x10}; - - // Checks whether s represents an integer smaller than the order of the group. - // This is needed to ensure that EdDSA signatures are non-malleable, as failing to check - // the range of S allows to modify signatures (cf. RFC 8032, Section 5.2.7 and Section 8.4.) - // @param s an integer in little-endian order. - private static boolean isSmallerThanGroupOrder(byte[] s) { - for (int j = Field25519.FIELD_LEN - 1; j >= 0; j--) { - // compare unsigned bytes - int a = s[j] & 0xff; - int b = GROUP_ORDER[j] & 0xff; - if (a != b) { - return a < b; - } - } - return false; - } - - /** - * Returns true if the EdDSA {@code signature} with {@code message}, can be verified with - * {@code publicKey}. - */ - public static boolean verify(final byte[] message, final byte[] signature, - final byte[] publicKey) { - try { - if (signature.length != SIGNATURE_LEN) { - return false; - } - if (publicKey.length != PUBLIC_KEY_LEN) { - return false; - } - byte[] s = Arrays.copyOfRange(signature, Field25519.FIELD_LEN, SIGNATURE_LEN); - if (!isSmallerThanGroupOrder(s)) { - return false; - } - MessageDigest digest = MessageDigest.getInstance("SHA-512"); - digest.update(signature, 0, Field25519.FIELD_LEN); - digest.update(publicKey); - digest.update(message); - byte[] h = digest.digest(); - reduce(h); - - XYZT negPublicKey = XYZT.fromBytesNegateVarTime(publicKey); - XYZ xyz = doubleScalarMultVarTime(h, negPublicKey, s); - byte[] expectedR = xyz.toBytes(); - for (int i = 0; i < Field25519.FIELD_LEN; i++) { - if (expectedR[i] != signature[i]) { - return false; - } - } - return true; - } catch (final GeneralSecurityException ignored) { - return false; - } - } -} diff --git a/nekobox-android/app/src/main/java/com/wireguard/crypto/Key.java b/nekobox-android/app/src/main/java/com/wireguard/crypto/Key.java deleted file mode 100644 index 9e25e60572..0000000000 --- a/nekobox-android/app/src/main/java/com/wireguard/crypto/Key.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright © 2017-2019 WireGuard LLC. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -package com.wireguard.crypto; - -import com.wireguard.crypto.KeyFormatException.Type; - -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.util.Arrays; - -/** - * Represents a WireGuard public or private key. This class uses specialized constant-time base64 - * and hexadecimal codec implementations that resist side-channel attacks. - *

- * Instances of this class are immutable. - */ -@SuppressWarnings("MagicNumber") -public final class Key { - private final byte[] key; - - /** - * Constructs an object encapsulating the supplied key. - * - * @param key an array of bytes containing a binary key. Callers of this constructor are - * responsible for ensuring that the array is of the correct length. - */ - private Key(final byte[] key) { - // Defensively copy to ensure immutability. - this.key = Arrays.copyOf(key, key.length); - } - - /** - * Decodes a single 4-character base64 chunk to an integer in constant time. - * - * @param src an array of at least 4 characters in base64 format - * @param srcOffset the offset of the beginning of the chunk in {@code src} - * @return the decoded 3-byte integer, or some arbitrary integer value if the input was not - * valid base64 - */ - private static int decodeBase64(final char[] src, final int srcOffset) { - int val = 0; - for (int i = 0; i < 4; ++i) { - final char c = src[i + srcOffset]; - val |= (-1 - + ((((('A' - 1) - c) & (c - ('Z' + 1))) >>> 8) & (c - 64)) - + ((((('a' - 1) - c) & (c - ('z' + 1))) >>> 8) & (c - 70)) - + ((((('0' - 1) - c) & (c - ('9' + 1))) >>> 8) & (c + 5)) - + ((((('+' - 1) - c) & (c - ('+' + 1))) >>> 8) & 63) - + ((((('/' - 1) - c) & (c - ('/' + 1))) >>> 8) & 64) - ) << (18 - 6 * i); - } - return val; - } - - /** - * Encodes a single 4-character base64 chunk from 3 consecutive bytes in constant time. - * - * @param src an array of at least 3 bytes - * @param srcOffset the offset of the beginning of the chunk in {@code src} - * @param dest an array of at least 4 characters - * @param destOffset the offset of the beginning of the chunk in {@code dest} - */ - private static void encodeBase64(final byte[] src, final int srcOffset, - final char[] dest, final int destOffset) { - final byte[] input = { - (byte) ((src[srcOffset] >>> 2) & 63), - (byte) ((src[srcOffset] << 4 | ((src[1 + srcOffset] & 0xff) >>> 4)) & 63), - (byte) ((src[1 + srcOffset] << 2 | ((src[2 + srcOffset] & 0xff) >>> 6)) & 63), - (byte) ((src[2 + srcOffset]) & 63), - }; - for (int i = 0; i < 4; ++i) { - dest[i + destOffset] = (char) (input[i] + 'A' - + (((25 - input[i]) >>> 8) & 6) - - (((51 - input[i]) >>> 8) & 75) - - (((61 - input[i]) >>> 8) & 15) - + (((62 - input[i]) >>> 8) & 3)); - } - } - - /** - * Decodes a WireGuard public or private key from its base64 string representation. This - * function throws a {@link KeyFormatException} if the source string is not well-formed. - * - * @param str the base64 string representation of a WireGuard key - * @return the decoded key encapsulated in an immutable container - */ - public static Key fromBase64(final String str) throws KeyFormatException { - final char[] input = str.toCharArray(); - if (input.length != Format.BASE64.length || input[Format.BASE64.length - 1] != '=') - throw new KeyFormatException(Format.BASE64, Type.LENGTH); - final byte[] key = new byte[Format.BINARY.length]; - int i; - int ret = 0; - for (i = 0; i < key.length / 3; ++i) { - final int val = decodeBase64(input, i * 4); - ret |= val >>> 31; - key[i * 3] = (byte) ((val >>> 16) & 0xff); - key[i * 3 + 1] = (byte) ((val >>> 8) & 0xff); - key[i * 3 + 2] = (byte) (val & 0xff); - } - final char[] endSegment = { - input[i * 4], - input[i * 4 + 1], - input[i * 4 + 2], - 'A', - }; - final int val = decodeBase64(endSegment, 0); - ret |= (val >>> 31) | (val & 0xff); - key[i * 3] = (byte) ((val >>> 16) & 0xff); - key[i * 3 + 1] = (byte) ((val >>> 8) & 0xff); - - if (ret != 0) - throw new KeyFormatException(Format.BASE64, Type.CONTENTS); - return new Key(key); - } - - /** - * Wraps a WireGuard public or private key in an immutable container. This function throws a - * {@link KeyFormatException} if the source data is not the correct length. - * - * @param bytes an array of bytes containing a WireGuard key in binary format - * @return the key encapsulated in an immutable container - */ - public static Key fromBytes(final byte[] bytes) throws KeyFormatException { - if (bytes.length != Format.BINARY.length) - throw new KeyFormatException(Format.BINARY, Type.LENGTH); - return new Key(bytes); - } - - /** - * Decodes a WireGuard public or private key from its hexadecimal string representation. This - * function throws a {@link KeyFormatException} if the source string is not well-formed. - * - * @param str the hexadecimal string representation of a WireGuard key - * @return the decoded key encapsulated in an immutable container - */ - public static Key fromHex(final String str) throws KeyFormatException { - final char[] input = str.toCharArray(); - if (input.length != Format.HEX.length) - throw new KeyFormatException(Format.HEX, Type.LENGTH); - final byte[] key = new byte[Format.BINARY.length]; - int ret = 0; - for (int i = 0; i < key.length; ++i) { - int c; - int cNum; - int cNum0; - int cAlpha; - int cAlpha0; - int cVal; - final int cAcc; - - c = input[i * 2]; - cNum = c ^ 48; - cNum0 = ((cNum - 10) >>> 8) & 0xff; - cAlpha = (c & ~32) - 55; - cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff; - ret |= ((cNum0 | cAlpha0) - 1) >>> 8; - cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha); - cAcc = cVal * 16; - - c = input[i * 2 + 1]; - cNum = c ^ 48; - cNum0 = ((cNum - 10) >>> 8) & 0xff; - cAlpha = (c & ~32) - 55; - cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff; - ret |= ((cNum0 | cAlpha0) - 1) >>> 8; - cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha); - key[i] = (byte) (cAcc | cVal); - } - if (ret != 0) - throw new KeyFormatException(Format.HEX, Type.CONTENTS); - return new Key(key); - } - - /** - * Generates a private key using the system's {@link SecureRandom} number generator. - * - * @return a well-formed random private key - */ - static Key generatePrivateKey() { - final SecureRandom secureRandom = new SecureRandom(); - final byte[] privateKey = new byte[Format.BINARY.getLength()]; - secureRandom.nextBytes(privateKey); - privateKey[0] &= 248; - privateKey[31] &= 127; - privateKey[31] |= 64; - return new Key(privateKey); - } - - /** - * Generates a public key from an existing private key. - * - * @param privateKey a private key - * @return a well-formed public key that corresponds to the supplied private key - */ - static Key generatePublicKey(final Key privateKey) { - final byte[] publicKey = new byte[Format.BINARY.getLength()]; - Curve25519.eval(publicKey, 0, privateKey.getBytes(), null); - return new Key(publicKey); - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) - return true; - if (obj == null || obj.getClass() != getClass()) - return false; - final Key other = (Key) obj; - return MessageDigest.isEqual(key, other.key); - } - - /** - * Returns the key as an array of bytes. - * - * @return an array of bytes containing the raw binary key - */ - public byte[] getBytes() { - // Defensively copy to ensure immutability. - return Arrays.copyOf(key, key.length); - } - - @Override - public int hashCode() { - int ret = 0; - for (int i = 0; i < key.length / 4; ++i) - ret ^= (key[i * 4 + 0] >> 0) + (key[i * 4 + 1] >> 8) + (key[i * 4 + 2] >> 16) + (key[i * 4 + 3] >> 24); - return ret; - } - - /** - * Encodes the key to base64. - * - * @return a string containing the encoded key - */ - public String toBase64() { - final char[] output = new char[Format.BASE64.length]; - int i; - for (i = 0; i < key.length / 3; ++i) - encodeBase64(key, i * 3, output, i * 4); - final byte[] endSegment = { - key[i * 3], - key[i * 3 + 1], - 0, - }; - encodeBase64(endSegment, 0, output, i * 4); - output[Format.BASE64.length - 1] = '='; - return new String(output); - } - - /** - * Encodes the key to hexadecimal ASCII characters. - * - * @return a string containing the encoded key - */ - public String toHex() { - final char[] output = new char[Format.HEX.length]; - for (int i = 0; i < key.length; ++i) { - output[i * 2] = (char) (87 + (key[i] >> 4 & 0xf) - + ((((key[i] >> 4 & 0xf) - 10) >> 8) & ~38)); - output[i * 2 + 1] = (char) (87 + (key[i] & 0xf) - + ((((key[i] & 0xf) - 10) >> 8) & ~38)); - } - return new String(output); - } - - /** - * The supported formats for encoding a WireGuard key. - */ - public enum Format { - BASE64(44), - BINARY(32), - HEX(64); - - private final int length; - - Format(final int length) { - this.length = length; - } - - public int getLength() { - return length; - } - } - -} diff --git a/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyFormatException.java b/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyFormatException.java deleted file mode 100644 index 5818b4d45b..0000000000 --- a/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyFormatException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -package com.wireguard.crypto; - -/** - * An exception thrown when attempting to parse an invalid key (too short, too long, or byte - * data inappropriate for the format). The format being parsed can be accessed with the - * {@link #getFormat} method. - */ -public final class KeyFormatException extends Exception { - private final Key.Format format; - private final Type type; - - KeyFormatException(final Key.Format format, final Type type) { - this.format = format; - this.type = type; - } - - public Key.Format getFormat() { - return format; - } - - public Type getType() { - return type; - } - - public enum Type { - CONTENTS, - LENGTH - } -} diff --git a/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyPair.java b/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyPair.java deleted file mode 100644 index f8238e91cc..0000000000 --- a/nekobox-android/app/src/main/java/com/wireguard/crypto/KeyPair.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright © 2017-2019 WireGuard LLC. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -package com.wireguard.crypto; - -/** - * Represents a Curve25519 key pair as used by WireGuard. - *

- * Instances of this class are immutable. - */ -public class KeyPair { - private final Key privateKey; - private final Key publicKey; - - /** - * Creates a key pair using a newly-generated private key. - */ - public KeyPair() { - this(Key.generatePrivateKey()); - } - - /** - * Creates a key pair using an existing private key. - * - * @param privateKey a private key, used to derive the public key - */ - public KeyPair(final Key privateKey) { - this.privateKey = privateKey; - publicKey = Key.generatePublicKey(privateKey); - } - - /** - * Returns the private key from the key pair. - * - * @return the private key - */ - public Key getPrivateKey() { - return privateKey; - } - - /** - * Returns the public key from the key pair. - * - * @return the public key - */ - public Key getPublicKey() { - return publicKey; - } -} diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/LogcatFragment.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/LogcatFragment.kt index bb4a082d74..2f276ee9fe 100644 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/LogcatFragment.kt +++ b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/LogcatFragment.kt @@ -75,13 +75,7 @@ class LogcatFragment : ToolbarFragment(R.layout.layout_logcat), offset += line.length + 1 } binding.textview.text = span - - // 阻止自动滚动/焦点干扰 - binding.scroolview.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS - binding.textview.isFocusable = false - binding.textview.isFocusableInTouchMode = false binding.textview.clearFocus() - // 等 textview 完成最终 layout 再滚动到底部 binding.textview.doOnLayout { binding.scroolview.scrollTo(0, binding.textview.height) diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/NetworkFragment.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/NetworkFragment.kt index 6ef29c114c..b8bb941451 100644 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/NetworkFragment.kt +++ b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/NetworkFragment.kt @@ -3,18 +3,9 @@ package io.nekohasekai.sagernet.ui import android.content.Intent import android.os.Bundle import android.view.View -import androidx.appcompat.app.AlertDialog import io.nekohasekai.sagernet.R -import io.nekohasekai.sagernet.database.DataStore -import io.nekohasekai.sagernet.database.ProfileManager import io.nekohasekai.sagernet.databinding.LayoutNetworkBinding -import io.nekohasekai.sagernet.databinding.LayoutProgressBinding -import io.nekohasekai.sagernet.ktx.* -import io.nekohasekai.sagernet.utils.Cloudflare -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.runBlocking +import io.nekohasekai.sagernet.ktx.app class NetworkFragment : NamedFragment(R.layout.layout_network) { @@ -27,58 +18,6 @@ class NetworkFragment : NamedFragment(R.layout.layout_network) { binding.stunTest.setOnClickListener { startActivity(Intent(requireContext(), StunActivity::class.java)) } - - //Markwon.create(requireContext()) - // .setMarkdown(binding.wrapLicense, getString(R.string.warp_license)) - - binding.warpGenerate.setOnClickListener { - runBlocking { - generateWarpConfiguration() - } - } - } - - suspend fun generateWarpConfiguration() { - val activity = requireActivity() as MainActivity - val binding = LayoutProgressBinding.inflate(layoutInflater).apply { - content.setText(R.string.generating) - } - var job: Job? = null - val dialog = AlertDialog.Builder(requireContext()) - .setView(binding.root) - .setCancelable(false) - .setNegativeButton(android.R.string.cancel) { _, _ -> - job?.cancel() - } - .show() - job = runOnDefaultDispatcher { - try { - val bean = Cloudflare.makeWireGuardConfiguration() - if (isActive) { - val groupId = DataStore.selectedGroupForImport() - if (DataStore.selectedGroup != groupId) { - DataStore.selectedGroup = groupId - } - onMainDispatcher { - activity.displayFragmentWithId(R.id.nav_configuration) - } - delay(1000L) - onMainDispatcher { - dialog.dismiss() - } - ProfileManager.createProfile(groupId, bean) - } - } catch (e: Exception) { - Logs.w(e) - onMainDispatcher { - if (isActive) { - dialog.dismiss() - activity.snackbar(e.readableMessage).show() - } - } - } - } - } } \ No newline at end of file diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/profile/ConfigEditActivity.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/profile/ConfigEditActivity.kt index ac8f046a85..e144a26ef6 100644 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/profile/ConfigEditActivity.kt +++ b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/ui/profile/ConfigEditActivity.kt @@ -86,7 +86,10 @@ class ConfigEditActivity : ThemedActivity() { } binding.actionTab.setOnClickListener { - binding.editor.insert(binding.editor.tab()) + try { + binding.editor.insert(binding.editor.tab()) + } catch (e: Exception) { + } } binding.actionUndo.setOnClickListener { try { @@ -107,7 +110,12 @@ class ConfigEditActivity : ThemedActivity() { } val extendedKeyboard = findViewById(R.id.extended_keyboard) - extendedKeyboard.setKeyListener { char -> binding.editor.insert(char) } + extendedKeyboard.setKeyListener { char -> + try { + binding.editor.insert(char) + } catch (e: Exception) { + } + } extendedKeyboard.setHasFixedSize(true) extendedKeyboard.submitList("{},:_\"".map { it.toString() }) extendedKeyboard.setBackgroundColor(getColorAttr(R.attr.primaryOrTextPrimary)) diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt deleted file mode 100644 index b70d854a06..0000000000 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt +++ /dev/null @@ -1,74 +0,0 @@ -package io.nekohasekai.sagernet.utils - -import com.wireguard.crypto.KeyPair -import io.nekohasekai.sagernet.database.DataStore -import io.nekohasekai.sagernet.fmt.wireguard.WireGuardBean -import io.nekohasekai.sagernet.ktx.Logs -import io.nekohasekai.sagernet.utils.cf.DeviceResponse -import io.nekohasekai.sagernet.utils.cf.RegisterRequest -import io.nekohasekai.sagernet.utils.cf.UpdateDeviceRequest -import libcore.Libcore -import moe.matsuri.nb4a.utils.JavaUtil.gson -import moe.matsuri.nb4a.utils.Util - -// kang from wgcf -object Cloudflare { - - private const val API_URL = "https://api.cloudflareclient.com" - private const val API_VERSION = "v0a1922" - - private const val CLIENT_VERSION_KEY = "CF-Client-Version" - private const val CLIENT_VERSION = "a-6.3-1922" - - fun makeWireGuardConfiguration(): WireGuardBean { - val keyPair = KeyPair() - val client = Libcore.newHttpClient().apply { - pinnedTLS12() - trySocks5(DataStore.mixedPort) - } - - try { - val response = client.newRequest().apply { - setMethod("POST") - setURL("$API_URL/$API_VERSION/reg") - setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION) - setHeader("Accept", "application/json") - setHeader("Content-Type", "application/json") - setContentString(RegisterRequest.newRequest(keyPair.publicKey)) - setUserAgent("okhttp/3.12.1") - }.execute() - - Logs.d(Util.getStringBox(response.contentString)) - val device = - gson.fromJson(Util.getStringBox(response.contentString), DeviceResponse::class.java) - val accessToken = device.token - - client.newRequest().apply { - setMethod("PATCH") - setURL(API_URL + "/" + API_VERSION + "/reg/" + device.id + "/account/reg/" + device.id) - setHeader("Accept", "application/json") - setHeader("Content-Type", "application/json") - setHeader("Authorization", "Bearer $accessToken") - setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION) - setContentString(UpdateDeviceRequest.newRequest()) - setUserAgent("okhttp/3.12.1") - }.execute() - - val peer = device.config.peers[0] - val localAddresses = device.config.interfaceX.addresses - return WireGuardBean().apply { - name = "CloudFlare Warp ${device.account.id}" - privateKey = keyPair.privateKey.toBase64() - peerPublicKey = peer.publicKey - serverAddress = peer.endpoint.host.substringBeforeLast(":") - serverPort = peer.endpoint.host.substringAfterLast(":").toInt() - localAddress = localAddresses.v4 + "/32" + "\n" + localAddresses.v6 + "/128" - mtu = 1280 - reserved = device.config.clientId - } - } finally { - client.close() - } - } - -} \ No newline at end of file diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt deleted file mode 100644 index 874304dc2a..0000000000 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt +++ /dev/null @@ -1,114 +0,0 @@ -package io.nekohasekai.sagernet.utils.cf - - -import com.google.gson.annotations.SerializedName - -data class DeviceResponse( - @SerializedName("created") - var created: String = "", - @SerializedName("type") - var type: String = "", - @SerializedName("locale") - var locale: String = "", - @SerializedName("enabled") - var enabled: Boolean = false, - @SerializedName("token") - var token: String = "", - @SerializedName("waitlist_enabled") - var waitlistEnabled: Boolean = false, - @SerializedName("install_id") - var installId: String = "", - @SerializedName("warp_enabled") - var warpEnabled: Boolean = false, - @SerializedName("name") - var name: String = "", - @SerializedName("fcm_token") - var fcmToken: String = "", - @SerializedName("tos") - var tos: String = "", - @SerializedName("model") - var model: String = "", - @SerializedName("id") - var id: String = "", - @SerializedName("place") - var place: Int = 0, - @SerializedName("config") - var config: Config = Config(), - @SerializedName("updated") - var updated: String = "", - @SerializedName("key") - var key: String = "", - @SerializedName("account") - var account: Account = Account() -) { - data class Config( - @SerializedName("peers") - var peers: List = listOf(), - @SerializedName("services") - var services: Services = Services(), - @SerializedName("interface") - var interfaceX: Interface = Interface(), - @SerializedName("client_id") - var clientId: String = "" - ) { - data class Peer( - @SerializedName("public_key") - var publicKey: String = "", - @SerializedName("endpoint") - var endpoint: Endpoint = Endpoint() - ) { - data class Endpoint( - @SerializedName("v6") - var v6: String = "", - @SerializedName("host") - var host: String = "", - @SerializedName("v4") - var v4: String = "" - ) - } - - data class Services( - @SerializedName("http_proxy") - var httpProxy: String = "" - ) - - data class Interface( - @SerializedName("addresses") - var addresses: Addresses = Addresses() - ) { - data class Addresses( - @SerializedName("v6") - var v6: String = "", - @SerializedName("v4") - var v4: String = "" - ) - } - } - - data class Account( - @SerializedName("account_type") - var accountType: String = "", - @SerializedName("role") - var role: String = "", - @SerializedName("referral_renewal_countdown") - var referralRenewalCountdown: Int = 0, - @SerializedName("created") - var created: String = "", - @SerializedName("usage") - var usage: Int = 0, - @SerializedName("warp_plus") - var warpPlus: Boolean = false, - @SerializedName("referral_count") - var referralCount: Int = 0, - @SerializedName("license") - var license: String = "", - @SerializedName("quota") - var quota: Int = 0, - @SerializedName("premium_data") - var premiumData: Int = 0, - @SerializedName("id") - var id: String = "", - @SerializedName("updated") - var updated: String = "" - ) -} \ No newline at end of file diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt deleted file mode 100644 index 34bbe7c164..0000000000 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package io.nekohasekai.sagernet.utils.cf - -import com.google.gson.Gson -import com.google.gson.annotations.SerializedName -import com.wireguard.crypto.Key -import java.text.SimpleDateFormat -import java.util.* - -data class RegisterRequest( - @SerializedName("fcm_token") var fcmToken: String = "", - @SerializedName("install_id") var installedId: String = "", - var key: String = "", - var locale: String = "", - var model: String = "", - var tos: String = "", - var type: String = "" -) { - - companion object { - fun newRequest(publicKey: Key): String { - val request = RegisterRequest() - request.fcmToken = "" - request.installedId = "" - request.key = publicKey.toBase64() - request.locale = "en_US" - request.model = "PC" - val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'000000'+08:00", Locale.US) - request.tos = format.format(Date()) - request.type = "Android" - return Gson().toJson(request) - } - } -} \ No newline at end of file diff --git a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt b/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt deleted file mode 100644 index e12915b41b..0000000000 --- a/nekobox-android/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.nekohasekai.sagernet.utils.cf - -import com.google.gson.Gson - -data class UpdateDeviceRequest( - var name: String, var active: Boolean -) { - companion object { - fun newRequest(name: String = "SagerNet Client", active: Boolean = true) = - Gson().toJson(UpdateDeviceRequest(name, active)) - } -} \ No newline at end of file diff --git a/nekobox-android/app/src/main/java/moe/matsuri/nb4a/net/LocalResolverImpl.kt b/nekobox-android/app/src/main/java/moe/matsuri/nb4a/net/LocalResolverImpl.kt index 27c08e3103..7de35b44e9 100644 --- a/nekobox-android/app/src/main/java/moe/matsuri/nb4a/net/LocalResolverImpl.kt +++ b/nekobox-android/app/src/main/java/moe/matsuri/nb4a/net/LocalResolverImpl.kt @@ -6,16 +6,14 @@ import android.os.CancellationSignal import android.system.ErrnoException import androidx.annotation.RequiresApi import io.nekohasekai.sagernet.SagerNet -import io.nekohasekai.sagernet.ktx.tryResumeWithException +import io.nekohasekai.sagernet.ktx.Logs +import io.nekohasekai.sagernet.ktx.runOnIoDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asExecutor -import kotlinx.coroutines.runBlocking import libcore.ExchangeContext import libcore.LocalDNSTransport import java.net.InetAddress import java.net.UnknownHostException -import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine object LocalResolverImpl : LocalDNSTransport { @@ -27,110 +25,126 @@ object LocalResolverImpl : LocalDNSTransport { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q } + override fun networkHandle(): Long { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + return SagerNet.underlyingNetwork?.networkHandle ?: 0 + } + return 0 + } + @RequiresApi(Build.VERSION_CODES.Q) override fun exchange(ctx: ExchangeContext, message: ByteArray) { - return runBlocking { - suspendCoroutine { continuation -> - val signal = CancellationSignal() - ctx.onCancel(signal::cancel) - val callback = object : DnsResolver.Callback { - override fun onAnswer(answer: ByteArray, rcode: Int) { - // exchange don't generate rcode error - ctx.rawSuccess(answer) - continuation.resume(Unit) - } + val signal = CancellationSignal() + ctx.onCancel(signal::cancel) - override fun onError(error: DnsResolver.DnsException) { - when (val cause = error.cause) { - is ErrnoException -> { - ctx.errnoCode(cause.errno) - continuation.resume(Unit) - return - } + val callback = object : DnsResolver.Callback { + override fun onAnswer(answer: ByteArray, rcode: Int) { + ctx.rawSuccess(answer) + } + + override fun onError(error: DnsResolver.DnsException) { + val cause = error.cause + if (cause is ErrnoException) { + ctx.errnoCode(cause.errno) + } else { + Logs.w(error) + ctx.errnoCode(114514) + } + } + } + + DnsResolver.getInstance().rawQuery( + SagerNet.underlyingNetwork, + message, + DnsResolver.FLAG_NO_RETRY, + Dispatchers.IO.asExecutor(), + signal, + callback + ) + } + + override fun lookup(ctx: ExchangeContext, network: String, domain: String) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val signal = CancellationSignal() + ctx.onCancel(signal::cancel) + + val callback = object : DnsResolver.Callback> { + override fun onAnswer(answer: Collection, rcode: Int) { + try { + if (rcode == 0) { + ctx.success(answer.mapNotNull { it.hostAddress }.joinToString("\n")) + } else { + ctx.errorCode(rcode) } - continuation.tryResumeWithException(error) + } catch (e: Exception) { + Logs.w(e) + ctx.errnoCode(114514) } } - DnsResolver.getInstance().rawQuery( + + override fun onError(error: DnsResolver.DnsException) { + try { + val cause = error.cause + if (cause is ErrnoException) { + ctx.errnoCode(cause.errno) + } else { + Logs.w(error) + ctx.errnoCode(114514) + } + } catch (e: Exception) { + Logs.w(e) + ctx.errnoCode(114514) + } + } + } + + val type = when { + network.endsWith("4") -> DnsResolver.TYPE_A + network.endsWith("6") -> DnsResolver.TYPE_AAAA + else -> null + } + if (type != null) { + DnsResolver.getInstance().query( SagerNet.underlyingNetwork, - message, + domain, + type, + DnsResolver.FLAG_NO_RETRY, + Dispatchers.IO.asExecutor(), + signal, + callback + ) + } else { + DnsResolver.getInstance().query( + SagerNet.underlyingNetwork, + domain, DnsResolver.FLAG_NO_RETRY, Dispatchers.IO.asExecutor(), signal, callback ) } - } - } - - override fun lookup(ctx: ExchangeContext, network: String, domain: String) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - return runBlocking { - suspendCoroutine { continuation -> - val signal = CancellationSignal() - ctx.onCancel(signal::cancel) - val callback = object : DnsResolver.Callback> { - override fun onAnswer(answer: Collection, rcode: Int) { - if (rcode == 0) { - ctx.success((answer as Collection).mapNotNull { it?.hostAddress } - .joinToString("\n")) - } else { - ctx.errorCode(rcode) - } - continuation.resume(Unit) - } - - override fun onError(error: DnsResolver.DnsException) { - when (val cause = error.cause) { - is ErrnoException -> { - ctx.errnoCode(cause.errno) - continuation.resume(Unit) - return - } - } - continuation.tryResumeWithException(error) - } - } - val type = when { - network.endsWith("4") -> DnsResolver.TYPE_A - network.endsWith("6") -> DnsResolver.TYPE_AAAA - else -> null - } - if (type != null) { - DnsResolver.getInstance().query( - SagerNet.underlyingNetwork, - domain, - type, - DnsResolver.FLAG_NO_RETRY, - Dispatchers.IO.asExecutor(), - signal, - callback - ) - } else { - DnsResolver.getInstance().query( - SagerNet.underlyingNetwork, - domain, - DnsResolver.FLAG_NO_RETRY, - Dispatchers.IO.asExecutor(), - signal, - callback - ) - } - } - } } else { - val answer = try { - val u = SagerNet.underlyingNetwork - if (u != null) { - u.getAllByName(domain) - } else { - InetAddress.getAllByName(domain) + runOnIoDispatcher { + // 老版本系统,继续用阻塞的 InetAddress + try { + val u = SagerNet.underlyingNetwork + val answer = if (u != null) { + u.getAllByName(domain) + } else { + InetAddress.getAllByName(domain) + } + if (answer != null) { + ctx.success(answer.mapNotNull { it.hostAddress }.joinToString("\n")) + } else { + ctx.errnoCode(114514) + } + } catch (e: UnknownHostException) { + ctx.errorCode(RCODE_NXDOMAIN) + } catch (e: Exception) { + Logs.w(e) + ctx.errnoCode(114514) } - } catch (e: UnknownHostException) { - ctx.errorCode(RCODE_NXDOMAIN) - return } - ctx.success(answer.mapNotNull { it.hostAddress }.joinToString("\n")) } } diff --git a/nekobox-android/app/src/main/res/layout/layout_network.xml b/nekobox-android/app/src/main/res/layout/layout_network.xml index a0df5bca06..e09df65b9d 100644 --- a/nekobox-android/app/src/main/res/layout/layout_network.xml +++ b/nekobox-android/app/src/main/res/layout/layout_network.xml @@ -60,61 +60,4 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/v2rayn/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs b/v2rayn/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs new file mode 100644 index 0000000000..5df0251acf --- /dev/null +++ b/v2rayn/v2rayN/v2rayN.Desktop/Views/ProfilesSelectWindow.axaml.cs @@ -0,0 +1,200 @@ +using System.Linq; +using System.Reactive.Disposables; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.VisualTree; +using Avalonia.ReactiveUI; +using ReactiveUI; +using ServiceLib.Manager; +using v2rayN.Desktop.Common; + +namespace v2rayN.Desktop.Views; + +public partial class ProfilesSelectWindow : ReactiveWindow +{ + private static Config _config; + + public Task ProfileItem => GetProfileItem(); + public Task?> ProfileItems => GetProfileItems(); + private bool _allowMultiSelect = false; + + public ProfilesSelectWindow() + { + InitializeComponent(); + + _config = AppManager.Instance.Config; + + btnAutofitColumnWidth.Click += BtnAutofitColumnWidth_Click; + txtServerFilter.KeyDown += TxtServerFilter_KeyDown; + lstProfiles.KeyDown += LstProfiles_KeyDown; + lstProfiles.SelectionChanged += LstProfiles_SelectionChanged; + lstProfiles.LoadingRow += LstProfiles_LoadingRow; + lstProfiles.Sorting += LstProfiles_Sorting; + lstProfiles.DoubleTapped += LstProfiles_DoubleTapped; + + ViewModel = new ProfilesSelectViewModel(UpdateViewHandler); + DataContext = ViewModel; + + this.WhenActivated(disposables => + { + this.OneWayBind(ViewModel, vm => vm.ProfileItems, v => v.lstProfiles.ItemsSource).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.SelectedProfile, v => v.lstProfiles.SelectedItem).DisposeWith(disposables); + + this.Bind(ViewModel, vm => vm.SelectedSub, v => v.lstGroup.SelectedItem).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.ServerFilter, v => v.txtServerFilter.Text).DisposeWith(disposables); + }); + + btnCancel.Click += (s, e) => Close(false); + } + + public void AllowMultiSelect(bool allow) + { + _allowMultiSelect = allow; + if (allow) + { + lstProfiles.SelectionMode = DataGridSelectionMode.Extended; + lstProfiles.SelectedItems.Clear(); + } + else + { + lstProfiles.SelectionMode = DataGridSelectionMode.Single; + if (lstProfiles.SelectedItems.Count > 0) + { + var first = lstProfiles.SelectedItems[0]; + lstProfiles.SelectedItems.Clear(); + lstProfiles.SelectedItem = first; + } + } + } + + // Expose ConfigType filter controls to callers + public void SetConfigTypeFilter(IEnumerable types, bool exclude = false) + => ViewModel?.SetConfigTypeFilter(types, exclude); + + private async Task UpdateViewHandler(EViewAction action, object? obj) + { + switch (action) + { + case EViewAction.CloseWindow: + Close(true); + break; + } + return await Task.FromResult(true); + } + + private void LstProfiles_SelectionChanged(object? sender, SelectionChangedEventArgs e) + { + if (ViewModel != null) + { + ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); + } + } + + private void LstProfiles_LoadingRow(object? sender, DataGridRowEventArgs e) + { + e.Row.Header = $" {e.Row.Index + 1}"; + } + + private void LstProfiles_DoubleTapped(object? sender, TappedEventArgs e) + { + // 忽略表头区域的双击 + if (e.Source is Control src) + { + if (src.FindAncestorOfType() != null) + { + e.Handled = true; + return; + } + + // 仅当在数据行或其子元素上双击时才触发选择 + if (src.FindAncestorOfType() != null) + { + ViewModel?.SelectFinish(); + e.Handled = true; + } + } + } + + private void LstProfiles_Sorting(object? sender, DataGridColumnEventArgs e) + { + // 自定义排序,防止默认行为导致误触发 + e.Handled = true; + if (ViewModel != null && e.Column?.Tag?.ToString() != null) + { + ViewModel.SortServer(e.Column.Tag.ToString()); + } + } + + private void LstProfiles_KeyDown(object? sender, KeyEventArgs e) + { + if (e.KeyModifiers is KeyModifiers.Control or KeyModifiers.Meta) + { + if (e.Key == Key.A) + { + if (_allowMultiSelect) + { + lstProfiles.SelectAll(); + } + e.Handled = true; + } + } + else + { + if (e.Key is Key.Enter or Key.Return) + { + ViewModel?.SelectFinish(); + e.Handled = true; + } + } + } + + private void BtnAutofitColumnWidth_Click(object? sender, RoutedEventArgs e) + { + AutofitColumnWidth(); + } + + private void AutofitColumnWidth() + { + try + { + foreach (var col in lstProfiles.Columns) + { + col.Width = new DataGridLength(1, DataGridLengthUnitType.Auto); + } + } + catch + { + } + } + + private void TxtServerFilter_KeyDown(object? sender, KeyEventArgs e) + { + if (e.Key is Key.Enter or Key.Return) + { + ViewModel?.RefreshServers(); + } + } + + public async Task GetProfileItem() + { + var item = await ViewModel?.GetProfileItem(); + return item; + } + + public async Task?> GetProfileItems() + { + var item = await ViewModel?.GetProfileItems(); + return item; + } + + private void BtnSave_Click(object sender, RoutedEventArgs e) + { + // Trigger selection finalize when Confirm is clicked + ViewModel?.SelectFinish(); + } +} diff --git a/v2rayn/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml b/v2rayn/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml index f310f26068..872a11f8d8 100644 --- a/v2rayn/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml +++ b/v2rayn/v2rayN/v2rayN.Desktop/Views/RoutingRuleDetailsWindow.axaml @@ -54,13 +54,22 @@ Width="300" Margin="{StaticResource Margin4}" Text="{Binding SelectedSource.OutboundTag, Mode=TwoWay}" /> - + VerticalAlignment="Center"> + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/v2rayn/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs b/v2rayn/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs new file mode 100644 index 0000000000..e9e33ec5ec --- /dev/null +++ b/v2rayn/v2rayN/v2rayN/Views/ProfilesSelectWindow.xaml.cs @@ -0,0 +1,194 @@ +using System.Reactive.Disposables; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Threading; +using ReactiveUI; +using ServiceLib.Manager; +using Splat; +using v2rayN.Base; + +namespace v2rayN.Views; + +public partial class ProfilesSelectWindow +{ + private static Config _config; + + public Task ProfileItem => GetProfileItem(); + public Task?> ProfileItems => GetProfileItems(); + private bool _allowMultiSelect = false; + + public ProfilesSelectWindow() + { + InitializeComponent(); + lstGroup.MaxHeight = Math.Floor(SystemParameters.WorkArea.Height * 0.20 / 40) * 40; + + _config = AppManager.Instance.Config; + + btnAutofitColumnWidth.Click += BtnAutofitColumnWidth_Click; + txtServerFilter.PreviewKeyDown += TxtServerFilter_PreviewKeyDown; + lstProfiles.PreviewKeyDown += LstProfiles_PreviewKeyDown; + lstProfiles.SelectionChanged += LstProfiles_SelectionChanged; + lstProfiles.LoadingRow += LstProfiles_LoadingRow; + + ViewModel = new ProfilesSelectViewModel(UpdateViewHandler); + + + this.WhenActivated(disposables => + { + this.OneWayBind(ViewModel, vm => vm.ProfileItems, v => v.lstProfiles.ItemsSource).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.SelectedProfile, v => v.lstProfiles.SelectedItem).DisposeWith(disposables); + + this.OneWayBind(ViewModel, vm => vm.SubItems, v => v.lstGroup.ItemsSource).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.SelectedSub, v => v.lstGroup.SelectedItem).DisposeWith(disposables); + this.Bind(ViewModel, vm => vm.ServerFilter, v => v.txtServerFilter.Text).DisposeWith(disposables); + }); + } + + public void AllowMultiSelect(bool allow) + { + _allowMultiSelect = allow; + if (allow) + { + lstProfiles.SelectionMode = DataGridSelectionMode.Extended; + lstProfiles.SelectedItems.Clear(); + } + else + { + lstProfiles.SelectionMode = DataGridSelectionMode.Single; + if (lstProfiles.SelectedItems.Count > 0) + { + var first = lstProfiles.SelectedItems[0]; + lstProfiles.SelectedItems.Clear(); + lstProfiles.SelectedItem = first; + } + } + } + + // Expose ConfigType filter controls to callers + public void SetConfigTypeFilter(IEnumerable types, bool exclude = false) + => ViewModel?.SetConfigTypeFilter(types, exclude); + + #region Event + + private async Task UpdateViewHandler(EViewAction action, object? obj) + { + switch (action) + { + case EViewAction.CloseWindow: + this.DialogResult = true; + break; + } + return await Task.FromResult(true); + } + + private void LstProfiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + { + if (ViewModel != null) + { + ViewModel.SelectedProfiles = lstProfiles.SelectedItems.Cast().ToList(); + } + } + + private void LstProfiles_LoadingRow(object? sender, DataGridRowEventArgs e) + { + e.Row.Header = $" {e.Row.GetIndex() + 1}"; + } + + private void LstProfiles_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + ViewModel?.SelectFinish(); + } + + private void LstProfiles_ColumnHeader_Click(object sender, RoutedEventArgs e) + { + var colHeader = sender as DataGridColumnHeader; + if (colHeader == null || colHeader.TabIndex < 0 || colHeader.Column == null) + { + return; + } + + var colName = ((MyDGTextColumn)colHeader.Column).ExName; + ViewModel?.SortServer(colName); + } + + private void menuSelectAll_Click(object sender, RoutedEventArgs e) + { + if (!_allowMultiSelect) + { + return; + } + lstProfiles.SelectAll(); + } + + private void LstProfiles_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) + { + switch (e.Key) + { + case Key.A: + menuSelectAll_Click(null, null); + e.Handled = true; + break; + } + } + else + { + if (e.Key is Key.Enter or Key.Return) + { + ViewModel?.SelectFinish(); + e.Handled = true; + } + } + } + + private void BtnAutofitColumnWidth_Click(object sender, RoutedEventArgs e) + { + AutofitColumnWidth(); + } + + private void AutofitColumnWidth() + { + try + { + foreach (var it in lstProfiles.Columns) + { + it.Width = new DataGridLength(1, DataGridLengthUnitType.Auto); + } + } + catch (Exception ex) + { + Logging.SaveLog("ProfilesView", ex); + } + } + + private void TxtServerFilter_PreviewKeyDown(object sender, KeyEventArgs e) + { + if (e.Key is Key.Enter or Key.Return) + { + ViewModel?.RefreshServers(); + e.Handled = true; + } + } + + public async Task GetProfileItem() + { + var item = await ViewModel?.GetProfileItem(); + return item; + } + + public async Task?> GetProfileItems() + { + var item = await ViewModel?.GetProfileItems(); + return item; + } + + private void BtnSave_Click(object sender, RoutedEventArgs e) + { + // Trigger selection finalize when Confirm is clicked + ViewModel?.SelectFinish(); + } + #endregion Event +} diff --git a/v2rayn/v2rayN/v2rayN/Views/ProfilesView.xaml.cs b/v2rayn/v2rayN/v2rayN/Views/ProfilesView.xaml.cs index 539886a8dd..c03fb0bd77 100644 --- a/v2rayn/v2rayN/v2rayN/Views/ProfilesView.xaml.cs +++ b/v2rayn/v2rayN/v2rayN/Views/ProfilesView.xaml.cs @@ -29,7 +29,7 @@ public partial class ProfilesView btnAutofitColumnWidth.Click += BtnAutofitColumnWidth_Click; txtServerFilter.PreviewKeyDown += TxtServerFilter_PreviewKeyDown; lstProfiles.PreviewKeyDown += LstProfiles_PreviewKeyDown; - lstProfiles.SelectionChanged += lstProfiles_SelectionChanged; + lstProfiles.SelectionChanged += LstProfiles_SelectionChanged; lstProfiles.LoadingRow += LstProfiles_LoadingRow; menuSelectAll.Click += menuSelectAll_Click; @@ -191,7 +191,7 @@ public partial class ProfilesView } } - private void lstProfiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + private void LstProfiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if (ViewModel != null) { diff --git a/v2rayn/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml b/v2rayn/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml index baa4d5436c..f24a38d704 100644 --- a/v2rayn/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml +++ b/v2rayn/v2rayN/v2rayN/Views/RoutingRuleDetailsWindow.xaml @@ -72,14 +72,24 @@ IsEditable="True" MaxDropDownHeight="1000" Style="{StaticResource DefComboBox}" /> - + Orientation="Horizontal"> +