@onekeyfe/hd-transport 1.2.0-alpha.2 → 1.2.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/__tests__/messages.test.js +122 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +351 -0
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +296 -0
  5. package/__tests__/protocol-v2.test.js +384 -108
  6. package/dist/constants.d.ts +5 -3
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/index.d.ts +920 -369
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +587 -251
  11. package/dist/protocols/index.d.ts +11 -5
  12. package/dist/protocols/index.d.ts.map +1 -1
  13. package/dist/protocols/v2/constants.d.ts +1 -0
  14. package/dist/protocols/v2/constants.d.ts.map +1 -1
  15. package/dist/protocols/v2/decode.d.ts +3 -2
  16. package/dist/protocols/v2/decode.d.ts.map +1 -1
  17. package/dist/protocols/v2/encode.d.ts +2 -3
  18. package/dist/protocols/v2/encode.d.ts.map +1 -1
  19. package/dist/protocols/v2/index.d.ts +0 -1
  20. package/dist/protocols/v2/index.d.ts.map +1 -1
  21. package/dist/protocols/v2/link-manager.d.ts +36 -0
  22. package/dist/protocols/v2/link-manager.d.ts.map +1 -0
  23. package/dist/protocols/v2/sequence-cursor.d.ts +5 -0
  24. package/dist/protocols/v2/sequence-cursor.d.ts.map +1 -0
  25. package/dist/protocols/v2/session.d.ts +18 -3
  26. package/dist/protocols/v2/session.d.ts.map +1 -1
  27. package/dist/protocols/v2/usb-transport-base.d.ts +31 -0
  28. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -0
  29. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  30. package/dist/serialization/protobuf/messages.d.ts.map +1 -1
  31. package/dist/types/messages.d.ts +534 -225
  32. package/dist/types/messages.d.ts.map +1 -1
  33. package/dist/types/transport.d.ts +5 -3
  34. package/dist/types/transport.d.ts.map +1 -1
  35. package/messages-protocol-v2.json +825 -709
  36. package/package.json +3 -3
  37. package/scripts/protobuf-build.sh +96 -310
  38. package/scripts/protobuf-patches/index.js +1 -0
  39. package/scripts/protobuf-types.js +12 -0
  40. package/src/constants.ts +21 -15
  41. package/src/index.ts +8 -0
  42. package/src/protocols/index.ts +25 -39
  43. package/src/protocols/v2/constants.ts +1 -0
  44. package/src/protocols/v2/crc8.ts +1 -1
  45. package/src/protocols/v2/decode.ts +38 -34
  46. package/src/protocols/v2/encode.ts +2 -28
  47. package/src/protocols/v2/index.ts +0 -1
  48. package/src/protocols/v2/link-manager.ts +162 -0
  49. package/src/protocols/v2/sequence-cursor.ts +10 -0
  50. package/src/protocols/v2/session.ts +132 -178
  51. package/src/protocols/v2/usb-transport-base.ts +194 -0
  52. package/src/serialization/protobuf/decode.ts +4 -1
  53. package/src/serialization/protobuf/messages.ts +6 -1
  54. package/src/types/messages.ts +636 -265
  55. package/src/types/transport.ts +3 -3
  56. package/dist/protocols/v2/debug.d.ts +0 -13
  57. package/dist/protocols/v2/debug.d.ts.map +0 -1
  58. package/src/protocols/v2/debug.ts +0 -26
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport",
3
- "version": "1.2.0-alpha.2",
3
+ "version": "1.2.0-alpha.20",
4
4
  "description": "Transport layer abstractions and utilities for OneKey hardware SDK.",
5
5
  "author": "OneKey",
6
6
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
@@ -16,7 +16,7 @@
16
16
  "test": "jest",
17
17
  "lint": "eslint .",
18
18
  "lint:fix": "eslint . --fix",
19
- "update-protobuf": "./scripts/protobuf-build.sh"
19
+ "update:protobuf": "./scripts/protobuf-build.sh"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@types/bytebuffer": "^5.0.42",
@@ -28,5 +28,5 @@
28
28
  "long": "^4.0.0",
29
29
  "protobufjs": "^6.11.2"
30
30
  },
31
- "gitHead": "6c183b7f7027f4b4d3db4f427f6360351a6c6680"
31
+ "gitHead": "5fbc1ada90fd3cfda7e5ef08be368cb452018733"
32
32
  }
@@ -2,35 +2,29 @@
2
2
 
3
3
  set -euxo pipefail
4
4
 
5
- echo $#
6
-
7
- PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
5
+ PARENT_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)
8
6
  PACKAGE_ROOT="$PARENT_PATH/.."
7
+ REPO_ROOT="$PARENT_PATH/../../.."
8
+ CORE_MESSAGES_DIR="$REPO_ROOT/packages/core/src/data/messages"
9
9
 
10
10
  SRC="../../submodules/firmware/common/protob"
11
11
  DIST="."
12
12
  LANG="typescript"
13
- # Absolute paths — resolved relative to this script's directory
14
- REPO_ROOT="$PARENT_PATH/../../.."
15
- CORE_MESSAGES_DIR="$REPO_ROOT/packages/core/src/data/messages"
16
13
 
17
- if [[ $# -ne 0 && $# -ne 3 ]]
18
- then
19
- echo "must provide either 3 or 0 arguments. $# provided"
20
- exit 1
14
+ if [[ $# -ne 0 && $# -ne 3 ]]; then
15
+ echo "must provide either 3 or 0 arguments. $# provided"
16
+ exit 1
21
17
  fi
22
18
 
23
- if [[ $# -eq 3 ]]
24
- then
25
- SRC=$1
26
- DIST=$2
27
- LANG=$3
19
+ if [[ $# -eq 3 ]]; then
20
+ SRC=$1
21
+ DIST=$2
22
+ LANG=$3
28
23
  fi
29
24
 
30
- if [[ "$LANG" != "typescript" && "$LANG" != "flow" ]];
31
- then
32
- echo "either typescript or flow must be specified as the third argument"
33
- exit 1
25
+ if [[ "$LANG" != "typescript" && "$LANG" != "flow" ]]; then
26
+ echo "either typescript or flow must be specified as the third argument"
27
+ exit 1
34
28
  fi
35
29
 
36
30
  if [[ "$SRC" = /* ]]; then
@@ -45,308 +39,100 @@ else
45
39
  DIST_PATH="$PACKAGE_ROOT/$DIST"
46
40
  fi
47
41
 
48
- # Remove temp proto files on any exit, including failure paths
49
- trap 'rm -f "$DIST_PATH/messages-tmp.proto" "$PARENT_PATH/messages-protocol-v2-tmp.proto"' EXIT
50
-
51
-
52
- # ============================================================
53
- # BUILD Pro1 messages.json (requires firmware submodule)
54
- # ============================================================
55
- # Combines all messages*.proto files from firmware submodule into
56
- # messages.json, then copies to core package.
57
- if [ -d "$SRC_PATH" ] && ls "$SRC_PATH"/messages*.proto 1>/dev/null 2>&1; then
58
- echo "=== Building Pro1 (legacy) protobuf messages ==="
59
- TMP_PROTO="$DIST_PATH/messages-tmp.proto"
60
- echo 'syntax = "proto2";' > "$TMP_PROTO"
61
- echo 'import "google/protobuf/descriptor.proto";' >> "$TMP_PROTO"
62
- echo "Build proto file from $SRC_PATH"
63
- grep -hv -e '^import ' -e '^syntax' -e '^package' -e 'option java_' "$SRC_PATH"/messages*.proto \
64
- | sed 's/ hw\.trezor\.messages\.common\./ /' \
65
- | sed 's/ common\./ /' \
66
- | sed 's/ ethereum_definitions\./ /' \
67
- | sed 's/ management\./ /' \
68
- | sed 's/^option /\/\/ option /' \
69
- | grep -v ' reserved '>> "$TMP_PROTO"
70
-
71
- npx pbjs -t json -p "$DIST_PATH" -o "$DIST_PATH/messages.json" --keep-case "$TMP_PROTO"
72
- rm "$TMP_PROTO"
73
-
74
- # Copy to core package
75
- cp "$DIST_PATH/messages.json" "$CORE_MESSAGES_DIR/messages.json"
76
- echo "Pro1 messages.json copied to core"
77
-
78
- yarn --cwd "$PACKAGE_ROOT" prettier --write "$DIST_PATH/messages.json"
79
- yarn --cwd "$PACKAGE_ROOT" prettier --write "$CORE_MESSAGES_DIR/messages.json"
80
- # Type generation (protobuf-types.js) runs once at the end of the Protocol V2
81
- # section below, after both schemas are available.
82
- else
83
- # Intentional asymmetry with the Protocol V2 section below: the legacy firmware
84
- # submodule is optional (the committed messages.json stays in use when it is
85
- # absent), while firmware-pro2 is the only source of the Protocol V2 schema,
86
- # so its absence is a hard error (exit 1).
87
- echo "⚠️ firmware submodule not found at $SRC_PATH"
88
- echo " Skipping Pro1 protobuf build. To enable:"
89
- echo " git submodule update --init submodules/firmware"
90
- fi
91
-
92
-
93
- # ============================================================
94
- # BUILD Protocol V2 messages-protocol-v2.json
95
- # ============================================================
96
- # Source of truth: submodules/firmware-pro2/sys/protobuf/onekey_protocol/.
97
- # Protocol V2 keeps chain/app protocols under legacy/ and system protocols under latest/.
98
- # The SDK flattens them into one protobuf schema for transport runtime, but it must keep
99
- # firmware message names and enum values intact. SDK-facing aliases belong in core/API code,
100
- # not in the protobuf schema.
101
- # ============================================================
102
- cd "$PARENT_PATH"
103
-
42
+ V1_TMP_PROTO="$DIST_PATH/messages-tmp.proto"
43
+ V2_TMP_PROTO="$PARENT_PATH/messages-protocol-v2-tmp.proto"
44
+ trap 'rm -f "$V1_TMP_PROTO" "$V2_TMP_PROTO"' EXIT
45
+
46
+ echo "=== Building Protocol V1 messages ==="
47
+ echo 'syntax = "proto2";' > "$V1_TMP_PROTO"
48
+ echo 'import "google/protobuf/descriptor.proto";' >> "$V1_TMP_PROTO"
49
+ grep -hv -e '^import ' -e '^syntax' -e '^package' -e 'option java_' "$SRC_PATH"/messages*.proto \
50
+ | sed 's/ hw\.trezor\.messages\.common\./ /' \
51
+ | sed 's/ common\./ /' \
52
+ | sed 's/ ethereum_definitions\./ /' \
53
+ | sed 's/ management\./ /' \
54
+ | sed 's/^option /\/\/ option /' \
55
+ | grep -v ' reserved ' >> "$V1_TMP_PROTO"
56
+
57
+ npx pbjs -t json -p "$DIST_PATH" -o "$DIST_PATH/messages.json" --keep-case "$V1_TMP_PROTO"
58
+ cp "$DIST_PATH/messages.json" "$CORE_MESSAGES_DIR/messages.json"
59
+
60
+ echo "=== Building Protocol V2 messages ==="
104
61
  SRC_PRO2_LEGACY="$REPO_ROOT/submodules/firmware-pro2/sys/protobuf/onekey_protocol/legacy"
105
62
  SRC_PRO2_LATEST="$REPO_ROOT/submodules/firmware-pro2/sys/protobuf/onekey_protocol/latest"
106
63
 
107
- if [ -d "$SRC_PRO2_LATEST" ] && ls "$SRC_PRO2_LATEST"/messages*.proto 1>/dev/null 2>&1; then
108
- echo "=== Building Protocol V2 messages from firmware-pro2 legacy + latest protobuf schema ==="
109
- TMP_PROTO="$PARENT_PATH/messages-protocol-v2-tmp.proto"
110
-
111
- {
112
- echo 'syntax = "proto2";'
113
- echo 'import "google/protobuf/descriptor.proto";'
114
- echo ''
115
-
116
- # Pro2 firmware keeps chain/app protocols under legacy/, and Protocol V2
117
- # device/filesystem/firmware protocols under latest/. Build one flat
118
- # schema so Protocol V2 framing can also encode legacy public-chain calls.
119
- grep -hv \
120
- -e '^import ' -e '^syntax' -e '^package' -e 'option java_' \
121
- "$SRC_PRO2_LEGACY"/messages*.proto \
122
- | sed 's/ hw\.onekey\.messages\.[a-zA-Z_]*\./ /g' \
123
- | sed 's/ crypto\./ /g' \
124
- | sed 's/ ethereum_definitions\./ /g' \
125
- | sed 's/ management\./ /g' \
126
- | sed 's/^option /\/\/ option /' \
127
- | grep -v ' reserved '
128
-
129
- if ! grep -q '^message TonSignData ' "$SRC_PRO2_LEGACY"/messages*.proto; then
130
- echo ''
131
- echo '// --- TON signData (kept until firmware-pro2 legacy proto exports it) ---'
132
- echo 'message TonSignData {'
133
- echo ' repeated uint32 address_n = 1;'
134
- echo ' required TonSignDataType type = 2;'
135
- echo ' required bytes payload = 3;'
136
- echo ' optional string schema = 4;'
137
- echo ' required string appdomain = 5;'
138
- echo ' required uint64 timestamp = 6;'
139
- echo ' optional string from_address = 7;'
140
- echo ' optional TonWalletVersion wallet_version = 8 [default=V4R2];'
141
- echo ' optional uint32 wallet_id = 9 [default=698983191];'
142
- echo ' optional TonWorkChain workchain = 10 [default=BASECHAIN];'
143
- echo ' optional bool is_bounceable = 11 [default=false];'
144
- echo ' optional bool is_testnet_only = 12 [default=false];'
145
- echo ''
146
- echo ' enum TonSignDataType {'
147
- echo ' TEXT = 0;'
148
- echo ' BINARY = 1;'
149
- echo ' CELL = 2;'
150
- echo ' }'
151
- echo '}'
152
- echo ''
153
- echo 'message TonSignedData {'
154
- echo ' optional bytes signature = 1;'
155
- echo ' optional bytes digest = 2;'
156
- echo '}'
157
- fi
158
-
159
- echo ''
160
- echo '// --- Protocol V2 system messages ---'
161
- grep -hv \
162
- -e '^import ' -e '^syntax' -e '^package' -e 'option java_' \
163
- -e '^option ' \
164
- "$SRC_PRO2_LATEST"/messages*.proto \
165
- | grep -v ' reserved '
166
-
167
- if ! grep -q '^message GetOnboardingStatus ' "$SRC_PRO2_LATEST"/messages*.proto; then
168
- echo ''
169
- echo '// --- Onboarding status (kept until firmware-pro2 latest proto exports it) ---'
170
- echo 'enum OnboardingStep {'
171
- echo ' ONBOARDING_STEP_UNKNOWN = 0;'
172
- echo ' ONBOARDING_STEP_DEVICE_VERIFICATION = 1;'
173
- echo ' ONBOARDING_STEP_PERSONALIZATION = 2;'
174
- echo ' ONBOARDING_STEP_SETUP = 3;'
175
- echo ' ONBOARDING_STEP_FIRMWARE = 4;'
176
- echo '}'
177
- echo ''
178
- echo 'message GetOnboardingStatus {'
179
- echo '}'
180
- echo ''
181
- echo 'message OnboardingStatus {'
182
- echo ' message Setup {'
183
- echo ' message NewDevice {'
184
- echo ' optional bool seedcard_backup = 1;'
185
- echo ' }'
186
- echo ' message Restore {'
187
- echo ' optional bool mnemonic = 1;'
188
- echo ' optional bool seedcard = 2;'
189
- echo ' }'
190
- echo ' optional NewDevice new_device = 1;'
191
- echo ' optional Restore restore = 2;'
192
- echo ' }'
193
- echo ' required OnboardingStep step = 1;'
194
- echo ' optional Setup setup = 2;'
195
- echo ' optional uint32 detail_code = 3;'
196
- echo ' optional string detail_str = 4;'
197
- echo '}'
198
- fi
199
- } > "$TMP_PROTO"
200
-
201
- if ! grep -q 'MessageType_TonSignData' "$TMP_PROTO"; then
202
- node - "$TMP_PROTO" <<'NODE'
203
- const fs = require('fs');
204
-
205
- const protoPath = process.argv[2];
206
- const proto = fs.readFileSync(protoPath, 'utf8');
207
- const updated = proto.replace(
208
- /( MessageType_TonTxAck\s*=\s*11907[^\n]*;\n)/,
209
- `$1 MessageType_TonSignData = 11908 [(wire_in) = true];\n MessageType_TonSignedData = 11909 [(wire_out) = true];\n`
210
- );
211
-
212
- if (updated === proto) {
213
- throw new Error('Unable to insert TON signData MessageType entries into Pro2 schema');
214
- }
215
-
216
- fs.writeFileSync(protoPath, updated);
217
- NODE
218
- fi
219
-
220
- if ! grep -q 'MessageType_GetOnboardingStatus' "$TMP_PROTO"; then
221
- node - "$TMP_PROTO" <<'NODE'
222
- const fs = require('fs');
223
-
224
- const protoPath = process.argv[2];
225
- const proto = fs.readFileSync(protoPath, 'utf8');
226
- const updated = proto.replace(
227
- /( MessageType_DeviceInfo\s*=\s*60601[^\n]*;\n)/,
228
- `$1 MessageType_GetOnboardingStatus = 60602;\n MessageType_OnboardingStatus = 60603;\n`
229
- );
230
-
231
- if (updated === proto) {
232
- throw new Error('Unable to insert onboarding MessageType entries into Pro2 schema');
233
- }
234
-
235
- fs.writeFileSync(protoPath, updated);
236
- NODE
237
- fi
64
+ if [[ ! -d "$SRC_PRO2_LEGACY" || ! -d "$SRC_PRO2_LATEST" ]]; then
65
+ echo "firmware-pro2 protobuf schema is missing"
66
+ exit 1
67
+ fi
238
68
 
239
- node - "$TMP_PROTO" <<'NODE'
69
+ {
70
+ echo 'syntax = "proto2";'
71
+ echo 'import "google/protobuf/descriptor.proto";'
72
+ echo ''
73
+ grep -hv \
74
+ -e '^import ' -e '^syntax' -e '^package' -e 'option java_' \
75
+ "$SRC_PRO2_LEGACY"/messages*.proto \
76
+ | sed 's/ hw\.onekey\.messages\.[a-zA-Z_]*\./ /g' \
77
+ | sed 's/ crypto\./ /g' \
78
+ | sed 's/ ethereum_definitions\./ /g' \
79
+ | sed 's/ management\./ /g' \
80
+ | sed 's/^option /\/\/ option /' \
81
+ | grep -v ' reserved '
82
+ echo ''
83
+ echo '// --- Protocol V2 system messages ---'
84
+ grep -hv \
85
+ -e '^import ' -e '^syntax' -e '^package' -e 'option java_' -e '^option ' \
86
+ "$SRC_PRO2_LATEST"/messages*.proto \
87
+ | grep -v ' reserved '
88
+ } > "$V2_TMP_PROTO"
89
+
90
+ # Protocol V2 latest schema defines common request names that also exist in
91
+ # legacy chain messages. Keep the legacy definitions and remove the duplicate
92
+ # top-level latest declarations before protobufjs parses the flattened schema.
93
+ node - "$V2_TMP_PROTO" <<'NODE'
240
94
  const fs = require('fs');
241
95
 
242
96
  const protoPath = process.argv[2];
243
- const proto = fs.readFileSync(protoPath, 'utf8');
244
- const messageNames = new Set(
245
- Array.from(proto.matchAll(/^\s*message\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{/gm)).map(
246
- match => match[1]
247
- )
248
- );
249
- const messageTypeNames = new Set(
250
- Array.from(proto.matchAll(/^\s*MessageType_([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)).map(
251
- match => match[1]
252
- )
253
- );
254
- const requiredMessages = [
255
- 'Ping',
256
- 'Success',
257
- 'Failure',
258
- 'DevReboot',
259
- 'DevGetDeviceInfo',
260
- 'DeviceInfo',
261
- 'DevFirmwareUpdate',
262
- 'DevFirmwareInstallProgress',
263
- 'DevGetFirmwareUpdateStatus',
264
- 'DevFirmwareUpdateStatus',
265
- 'FilesystemFixPermission',
266
- 'FilesystemPathInfo',
267
- 'FilesystemPathInfoQuery',
268
- 'FilesystemFile',
269
- 'FilesystemFileRead',
270
- 'FilesystemFileWrite',
271
- 'FilesystemFileDelete',
272
- 'FilesystemDir',
273
- 'FilesystemDirList',
274
- 'FilesystemDirMake',
275
- 'FilesystemDirRemove',
276
- 'FilesystemFormat',
277
- 'TonSignData',
278
- 'TonSignedData',
279
- 'GetOnboardingStatus',
280
- 'OnboardingStatus',
281
- ];
282
- const missingMessages = requiredMessages.filter(name => !messageNames.has(name));
283
- const missingMessageTypes = requiredMessages.filter(name => !messageTypeNames.has(name));
284
-
285
- if (missingMessages.length > 0 || missingMessageTypes.length > 0) {
286
- throw new Error(
287
- `Protocol V2 schema missing required entries: messages=[${missingMessages.join(
288
- ', '
289
- )}], messageTypes=[${missingMessageTypes.join(
290
- ', '
291
- )}]. Make sure submodules/firmware-pro2 is checked out on branch dev_romloader_split ` +
292
- '(origin/dev_romloader_split), which contains the Filesystem*/DevFirmwareUpdate/DevReboot messages.'
293
- );
97
+ let proto = fs.readFileSync(protoPath, 'utf8');
98
+
99
+ function removeLastTopLevelMessage(source, name) {
100
+ const pattern = new RegExp(`(^|\\n)message\\s+${name}\\s*\\{`, 'gm');
101
+ const matches = Array.from(source.matchAll(pattern));
102
+ if (matches.length < 2) return source;
103
+ const match = matches[matches.length - 1];
104
+ const start = match.index + (match[1] ? match[1].length : 0);
105
+ let depth = 0;
106
+ for (let index = start; index < source.length; index += 1) {
107
+ if (source[index] === '{') depth += 1;
108
+ if (source[index] === '}') {
109
+ depth -= 1;
110
+ if (depth === 0) {
111
+ let end = index + 1;
112
+ while (end < source.length && /\\s/.test(source[end])) end += 1;
113
+ return `${source.slice(0, start)}${source.slice(end)}`;
114
+ }
115
+ }
116
+ }
117
+ throw new Error(`Unterminated message block: ${name}`);
294
118
  }
295
119
 
296
- // Provisional wire IDs injected by this script for messages the firmware proto does
297
- // not export yet (pending firmware confirmation, see
298
- // docs/protocol-v2-deviceinfo-field-gaps.md). If the firmware submodule starts
299
- // exporting these MessageType entries itself, the injection above is skipped and the
300
- // firmware-assigned IDs flow into TMP_PROTO — assert they still match the IDs the SDK
301
- // was built against, and fail loudly on any drift.
302
- const expectedInjectedIds = {
303
- TonSignData: 11908,
304
- TonSignedData: 11909,
305
- GetOnboardingStatus: 60602,
306
- OnboardingStatus: 60603,
307
- };
308
- const actualIds = {};
309
- for (const match of proto.matchAll(/^\s*MessageType_([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(\d+)/gm)) {
310
- actualIds[match[1]] = Number(match[2]);
311
- }
312
- const idMismatches = Object.entries(expectedInjectedIds)
313
- .filter(([name, id]) => name in actualIds && actualIds[name] !== id)
314
- .map(([name, id]) => `${name}: expected ${id}, firmware proto has ${actualIds[name]}`);
120
+ ['Initialize', 'GetFeatures', 'OnekeyGetFeatures', 'Features'].forEach(name => {
121
+ proto = removeLastTopLevelMessage(proto, name);
122
+ });
315
123
 
316
- if (idMismatches.length > 0) {
317
- throw new Error(
318
- `Protocol V2 injected MessageType wire IDs conflict with the firmware proto: ${idMismatches.join(
319
- '; '
320
- )}. Update the injected IDs in protobuf-build.sh and the registry section in ` +
321
- 'docs/protocol-v2-deviceinfo-field-gaps.md.'
322
- );
323
- }
124
+ fs.writeFileSync(protoPath, proto);
324
125
  NODE
325
126
 
326
- npx pbjs -t json \
327
- -p "$PARENT_PATH" \
328
- -o "$PARENT_PATH/../messages-protocol-v2.json" \
329
- --keep-case \
330
- "$(basename "$TMP_PROTO")"
127
+ npx pbjs -t json -p "$PARENT_PATH" -o "$PACKAGE_ROOT/messages-protocol-v2.json" --keep-case "$V2_TMP_PROTO"
128
+ cp "$PACKAGE_ROOT/messages-protocol-v2.json" "$CORE_MESSAGES_DIR/messages-protocol-v2.json"
331
129
 
332
- rm -f "$TMP_PROTO"
333
-
334
- cp "$PARENT_PATH/../messages-protocol-v2.json" "$CORE_MESSAGES_DIR/messages-protocol-v2.json"
335
- echo "Protocol V2 messages-protocol-v2.json generated from firmware-pro2 legacy + latest schema and copied to core"
336
-
337
- yarn --cwd "$PACKAGE_ROOT" prettier --write "$PARENT_PATH/../messages-protocol-v2.json"
338
- yarn --cwd "$PACKAGE_ROOT" prettier --write "$CORE_MESSAGES_DIR/messages-protocol-v2.json"
130
+ echo "generating type definitions for: $LANG"
131
+ cd "$PARENT_PATH"
132
+ node ./protobuf-types.js "$LANG"
339
133
 
340
- echo "generating type definitions for: $LANG"
341
- node ./protobuf-types.js $LANG
342
- yarn --cwd "$PACKAGE_ROOT" prettier --write "$PACKAGE_ROOT/src/types/messages.ts"
343
- echo "=== Protocol V2 messages build complete ==="
344
- else
345
- # Unlike the optional Pro1 (legacy) section above, the firmware-pro2 submodule is
346
- # the only source of the Protocol V2 schema, so a missing checkout is a hard error.
347
- echo "firmware-pro2 latest protobuf schema not found at $SRC_PRO2_LATEST"
348
- echo "The Protocol V2 schema requires firmware-pro2 on branch dev_romloader_split."
349
- echo "Run: git submodule update --init submodules/firmware-pro2"
350
- echo "Then: git -C submodules/firmware-pro2 fetch origin dev_romloader_split && git -C submodules/firmware-pro2 checkout origin/dev_romloader_split"
351
- exit 1
352
- fi
134
+ yarn --cwd "$PACKAGE_ROOT" prettier --write "$DIST_PATH/messages.json"
135
+ yarn --cwd "$PACKAGE_ROOT" prettier --write "$CORE_MESSAGES_DIR/messages.json"
136
+ yarn --cwd "$PACKAGE_ROOT" prettier --write "$PACKAGE_ROOT/messages-protocol-v2.json"
137
+ yarn --cwd "$PACKAGE_ROOT" prettier --write "$CORE_MESSAGES_DIR/messages-protocol-v2.json"
138
+ yarn --cwd "$PACKAGE_ROOT" prettier --write "$PACKAGE_ROOT/src/types/messages.ts"
@@ -210,6 +210,7 @@ const TYPE_PATCH = {
210
210
  'TonSignMessage.ext_ton_amount': UINT_TYPE,
211
211
  'TonSignData.timestamp': UINT_TYPE,
212
212
  'TonSignProof.expire_at': UINT_TYPE,
213
+ 'TonSignData.timestamp': UINT_TYPE,
213
214
  };
214
215
 
215
216
  const DEFINITION_PATCH = {
@@ -19,6 +19,10 @@ const optionalJsonFiles = ['../messages-protocol-v2.json'];
19
19
  const OPTIONAL_DUPLICATE_TYPE_ALIASES = {
20
20
  DeviceInfo: 'ProtocolV2DeviceInfo',
21
21
  };
22
+ const OPTIONAL_NESTED_TYPE_ALIASES = [
23
+ { parent: 'Failure', name: 'FailureType', alias: 'ProtocolV2FailureType' },
24
+ { parent: 'Features', name: 'Capability', alias: 'ProtocolV2Capability' },
25
+ ];
22
26
  const messageTypeAliases = {};
23
27
  const skipMessageTypeKeys = new Set(Object.values(OPTIONAL_DUPLICATE_TYPE_ALIASES));
24
28
 
@@ -53,12 +57,16 @@ const ENUM_KEYS = [
53
57
  'InputScriptType',
54
58
  'OutputScriptType',
55
59
  'RequestType',
60
+ 'KaspaInputScriptType',
61
+ 'KaspaOutputScriptType',
62
+ 'KaspaRequestType',
56
63
  'BackupType',
57
64
  'Capability',
58
65
  'SafetyCheckLevel',
59
66
  'ButtonRequestType',
60
67
  'PinMatrixRequestType',
61
68
  'WordRequestType',
69
+ 'ProtocolV2Capability',
62
70
  ];
63
71
 
64
72
  const parseEnumTypescript = (itemName, item) => {
@@ -317,6 +325,10 @@ optionalJsonFiles.forEach(jsonFile => {
317
325
  const jsonPath = path.join(__dirname, jsonFile);
318
326
  if (!fs.existsSync(jsonPath)) return;
319
327
  const optionalJson = readJson(jsonPath);
328
+ OPTIONAL_NESTED_TYPE_ALIASES.forEach(({ parent, name, alias }) => {
329
+ const definition = optionalJson.nested[parent]?.nested?.[name];
330
+ if (definition) optionalJson.nested[alias] = definition;
331
+ });
320
332
  optionalJsons.push(optionalJson);
321
333
  Object.keys(optionalJson.nested).forEach(e => {
322
334
  if (!json.nested[e]) return; // V2-only type, parsed after the V1 pass below
package/src/constants.ts CHANGED
@@ -1,44 +1,50 @@
1
1
  // ---- Protocol V1 (Pro1 / Touch / Mini / Classic) ----
2
2
 
3
- /** Protocol V1 USB report 标记,ASCII '?'。 */
3
+ /** Protocol V1 USB report marker, ASCII `?`. */
4
4
  export const PROTOCOL_V1_REPORT_ID = 0x3f;
5
5
 
6
- /** Protocol V1 envelope 头部标记,ASCII '#'。 */
6
+ /** Protocol V1 envelope marker, ASCII `#`. */
7
7
  export const PROTOCOL_V1_HEADER_BYTE = 0x23;
8
8
 
9
- /** Protocol V1 单个 chunk 去掉 report 标记后的可用 payload 长度。 */
9
+ /** Protocol V1 payload bytes per chunk after the report marker. */
10
10
  export const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
11
11
 
12
- /** Protocol V1 USB packet 长度:report 标记 + chunk payload */
12
+ /** Protocol V1 USB packet length: report marker plus chunk payload. */
13
13
  export const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
14
14
 
15
- /** Protocol V1 message metadata:message type 2 字节 + payload length 4 字节。 */
15
+ /** Protocol V1 message metadata: two-byte type plus four-byte payload length. */
16
16
  export const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
17
17
 
18
- /** Protocol V1 envelope metadata:## + message type + payload length */
18
+ /** Protocol V1 envelope metadata: `##`, message type, and payload length. */
19
19
  export const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
20
20
 
21
21
  // ---- Protocol V2 (Pro2 USB / BLE transports) ----
22
22
 
23
- /** Protocol V2 单帧最大长度,包含 header、payload CRC;需容纳 4096 数据块及 protobuf 开销。 */
24
- export const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
23
+ /** Firmware Proto Link runtime limit for a complete V2 frame, including header and CRC. */
24
+ export const PROTOCOL_V2_FRAME_MAX_BYTES = 4200;
25
25
 
26
- /** WebUSB FilesystemFileWrite 的文件数据分块大小。 */
27
- export const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4096;
26
+ /** FilesystemFileWrite chunk size over WebUSB. */
27
+ export const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4000;
28
28
 
29
- /** BLE FilesystemFileWrite 的文件数据分块大小。 */
29
+ /** FilesystemFileWrite chunk size over BLE. */
30
30
  export const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
31
31
 
32
- /** @deprecated 使用按传输区分的 PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE / PROTOCOL_V2_BLE_FILE_CHUNK_SIZE。 */
32
+ /** BLE FilesystemFileRead chunk size, limited by the Pro2 1024-byte UART TX buffer. */
33
+ export const PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = 900;
34
+
35
+ /** Pro2 BLE/UART RX FIFO must hold a complete Proto Link frame. */
36
+ export const PROTOCOL_V2_BLE_FRAME_MAX_BYTES = 2048;
37
+
38
+ /** @deprecated Use the transport-specific WebUSB or BLE file chunk constant. */
33
39
  export const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
34
40
 
35
41
  /**
36
- * Protocol V2 路由 channel
37
- * USB 端点直接到主 MCU,不需要 proto-link 路由;BLE 需要经过 BLE 协处理器 UART bridge
42
+ * Protocol V2 routing channel. USB reaches the main MCU directly, while BLE routes
43
+ * through the BLE coprocessor UART bridge.
38
44
  */
39
45
  export const PROTOCOL_V2_CHANNEL_USB = 0;
40
46
  export const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
41
47
  export const PROTOCOL_V2_CHANNEL_SOCKET = 2;
42
48
 
43
- /** protobuf 命令流的 packet_src,固件侧会把 0 路由到 protobuf dispatcher */
49
+ /** packet_src for protobuf commands; firmware routes zero to the protobuf dispatcher. */
44
50
  export const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
package/src/index.ts CHANGED
@@ -10,8 +10,11 @@ import {
10
10
  } from './serialization';
11
11
  import { PROTOCOL_V2_SYS_MESSAGE_THRESHOLD, ProtocolV1, ProtocolV2 } from './protocols';
12
12
  import * as protocolV2Codec from './protocols/v2';
13
+ import { ProtocolV2LinkManager } from './protocols/v2/link-manager';
14
+ import { ProtocolV2UsbTransportBase } from './protocols/v2/usb-transport-base';
13
15
  import {
14
16
  ProtocolV2FrameAssembler,
17
+ ProtocolV2SequenceCursor,
15
18
  ProtocolV2Session,
16
19
  bytesToHex,
17
20
  concatUint8Arrays,
@@ -49,6 +52,8 @@ export * from './protocols';
49
52
  export * as protocolV1 from './protocols/v1';
50
53
  export * as protocolV2 from './protocols/v2';
51
54
  export * from './protocols/v2/session';
55
+ export * from './protocols/v2/link-manager';
56
+ export * from './protocols/v2/usb-transport-base';
52
57
 
53
58
  export default {
54
59
  check,
@@ -58,7 +63,10 @@ export default {
58
63
  ProtocolV2,
59
64
  PROTOCOL_V2_SYS_MESSAGE_THRESHOLD,
60
65
  ProtocolV2FrameAssembler,
66
+ ProtocolV2LinkManager,
67
+ ProtocolV2SequenceCursor,
61
68
  ProtocolV2Session,
69
+ ProtocolV2UsbTransportBase,
62
70
  bytesToHex,
63
71
  concatUint8Arrays,
64
72
  createMessageFromName,