@babylonlabs-io/ledger-vault-signer 0.0.1 → 0.4.0

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.
package/LICENSE ADDED
@@ -0,0 +1,169 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+
7
+ -----------------------------------------------------------------------------
8
+
9
+ Parameters
10
+
11
+ Licensor: Babylon Labs Ltd.
12
+
13
+ Licensed Work: @babylonlabs-io/ledger-vault-signer
14
+ The Licensed Work is (c) 2024 Babylon Labs Ltd.
15
+
16
+ Additional Use Grant:
17
+
18
+ In addition to the uses permitted under the non-production license below,
19
+ we grant you a limited, non-exclusive, non-transferable, non-sublicensable,
20
+ revocable license, limited as set forth below, to use the Licensed Work
21
+ in this repository for production commercial uses built on or using and integrated
22
+ with the Babylon Protocol, not including Competing Uses.
23
+
24
+ Any use beyond the scope of this license, including uses that are not built on or
25
+ using and integrated with the Babylon Protocol, or are Competing Uses,
26
+ will terminate this license to you, automatically and without notice.
27
+
28
+ This License applies separately and solely to the specific versions of the Licensed Work
29
+ in the specified repository on or before the date of this License, and we may require a
30
+ different license and different provisions for each subsequent version of the
31
+ Licensed Work released by us.
32
+
33
+ "Babylon Labs", "we", "our", or "us" means Babylon Labs Ltd.
34
+
35
+ "Babylon Protocol" means the Bitcoin staking protocol as further described in the documentation
36
+ here (https://docs.babylonlabs.io/docs/introduction/babylon-overview), as updated from time to time.
37
+
38
+ "Competing Use" means any use of the Licensed Work in any product, software, protocol, network,
39
+ application, or service that is made available to any party and that
40
+ (i) substitutes for the use of the Babylon Protocol,
41
+ (ii) offers the same or substantially similar functionality as the Babylon Protocol or
42
+ (iii) is built on or uses a protocol with substantially similar functionality as the Babylon Protocol
43
+ or otherwise facilitates the staking of bitcoin other than by utilizing the Babylon Protocol.
44
+
45
+ The provisions in this License apply to each individual, entity, group, or association
46
+ (each and collectively, "you" or "your") who uses the Licensed Work for production,
47
+ and you agree to such provisions. Your production use of the Licensed Work is conditional on your
48
+ agreement to this License. If you do not agree and consent to be bound to this License,
49
+ do not so use the Software.
50
+
51
+ If you do not fall within the limited scope of this license as described above or below,
52
+ or are otherwise not in strict compliance with this License, then this production license does not
53
+ extend to you and does not grant you any production use, including any copying, distributing, or
54
+ making any derivative use of the Licensed Work for production purposes.
55
+
56
+ Limited Scope of License. Your commercial production license to the Licensed Work
57
+ under this License does not extend to any use:
58
+
59
+ 1. unless you have legal capacity to consent and agree to be bound by this License;
60
+ 2. unless you have the technical knowledge necessary or advisable to understand and evaluate the
61
+ risks of using the Licensed Work and the Babylon Protocol;
62
+ 3. if you are a resident or agent of, or an entity organized, incorporated or doing business in,
63
+ Afghanistan, Belarus, Bosnia and Herzegovina, Burundi, Central African Republic, Crimea, Cuba,
64
+ Democratic People's Republic of Korea, Democratic Republic of the Congo,
65
+ Donetsk or Luhansk Regions of Ukraine, Eritrea, Guinea, Guinea-Bissau, Haiti, Iran, Iraq, Lebanon,
66
+ Libya, Mali, Myanmar, Nicaragua, Russia, Somalia, South Sudan, Sudan, Syria, Venezuela, Yemen,
67
+ or Zimbabwe or any other country to which the United States, the United Kingdom,
68
+ the European Union or any of its member states or the United Nations or any of its member states
69
+ (collectively, the "Major Jurisdictions") embargoes goods or imposes sanctions
70
+ (such embargoed or sanctioned territories, collectively, the "Restricted Territories");
71
+ 4. if you are, or if you directly or indirectly own or control, from any person or entity that is
72
+ listed on any sanctions list or equivalent maintained by any of the Major Jurisdictions
73
+ (collectively, "Sanctions Lists Persons");
74
+ 5. to transact in or with any Restricted Territories or Sanctions List Persons;
75
+ 6. if you are a U.S. Person as defined in 17 CFR § 230.902, or currently or ordinarily located or
76
+ resident in (or incorporated or organized in) the United States of America, Canada, or
77
+ Australia (collectively, "Excluded Jurisdictions"), or to transact in or with Excluded Jurisdictions;
78
+ 7. to defraud, or otherwise materially mislead, any person;
79
+ 8. in violation of applicable laws, rules or regulations in your relevant jurisdiction;
80
+ 9. that circumvents any sanctions or export controls targeting you or the country or territory where
81
+ you are located; or
82
+ 10. in any activity that transmits, exchanges, or is otherwise supported by the direct or indirect
83
+ proceeds of criminal or fraudulent activity.
84
+
85
+ Any production use of the Licensed Work by you confirms your agreement to the foregoing limitations,
86
+ and your understanding and agreement that they are limitations and not restrictions.
87
+
88
+ Change Date: 2027-03-15 (March 15th, 2027)
89
+
90
+ Change License: Apache 2.0
91
+
92
+ -----------------------------------------------------------------------------
93
+
94
+ Terms
95
+
96
+ The Licensor hereby grants you the right to copy, modify, create derivative
97
+ works, redistribute, and make non-production use of the Licensed Work. The
98
+ Licensor may make an Additional Use Grant, above, permitting limited
99
+ production use.
100
+
101
+ Effective on the Change Date, or the fourth anniversary of the first publicly
102
+ available distribution of a specific version of the Licensed Work under this
103
+ License, whichever comes first, the Licensor hereby grants you rights under
104
+ the terms of the Change License, and the rights granted in the paragraph
105
+ above terminate.
106
+
107
+ If your use of the Licensed Work does not comply with the requirements
108
+ currently in effect as described in this License, you must purchase a
109
+ commercial license from the Licensor, its affiliated entities, or authorized
110
+ resellers, or you must refrain from using the Licensed Work.
111
+
112
+ All copies of the original and modified Licensed Work, and derivative works
113
+ of the Licensed Work, are subject to this License. This License applies
114
+ separately for each version of the Licensed Work and the Change Date may vary
115
+ for each version of the Licensed Work released by Licensor.
116
+
117
+ You must conspicuously display this License on each original or modified copy
118
+ of the Licensed Work. If you receive the Licensed Work in original or
119
+ modified form from a third party, the terms and conditions set forth in this
120
+ License apply to your use of that work.
121
+
122
+ Any use of the Licensed Work in violation of this License will automatically
123
+ terminate your rights under this License for the current and all other
124
+ versions of the Licensed Work.
125
+
126
+ This License does not grant you any right in any trademark or logo of
127
+ Licensor or its affiliates (provided that you may use a trademark or logo of
128
+ Licensor as expressly required by this License).
129
+
130
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
131
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
132
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
133
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
134
+ TITLE.
135
+
136
+ MariaDB hereby grants you permission to use this License’s text to license
137
+ your works, and to refer to it using the trademark "Business Source License",
138
+ as long as you comply with the Covenants of Licensor below.
139
+
140
+ -----------------------------------------------------------------------------
141
+
142
+ Covenants of Licensor
143
+
144
+ In consideration of the right to use this License’s text and the "Business
145
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
146
+ other recipients of the licensed work to be provided by Licensor:
147
+
148
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
149
+ or a license that is compatible with GPL Version 2.0 or a later version,
150
+ where "compatible" means that software provided under the Change License can
151
+ be included in a program with software provided under GPL Version 2.0 or a
152
+ later version. Licensor may specify additional Change Licenses without
153
+ limitation.
154
+
155
+ 2. To either: (a) specify an additional grant of rights to use that does not
156
+ impose any additional restriction on the right granted in this License, as
157
+ the Additional Use Grant; or (b) insert the text "None".
158
+
159
+ 3. To specify a Change Date.
160
+
161
+ 4. Not to modify this License in any other way.
162
+
163
+ -----------------------------------------------------------------------------
164
+
165
+ Notice
166
+
167
+ The Business Source License (this document, or the "License") is not an Open
168
+ Source license. However, the Licensed Work will eventually be made available
169
+ under an Open Source License, as stated in this License.
@@ -0,0 +1,224 @@
1
+ # Third-party notices
2
+
3
+ This file covers third-party source vendored into this repository's package tree.
4
+ It is not an exhaustive inventory of every bundled npm dependency — those retain
5
+ their own license files. Vendored source:
6
+
7
+ ---
8
+
9
+ ## Ledger Bitcoin JS client
10
+
11
+ - Project: LedgerHQ/app-bitcoin (formerly app-bitcoin-new)
12
+ - Source: https://github.com/LedgerHQ/app-bitcoin
13
+ - Version: ledger-bitcoin@0.3.0 (commit 0a9e9e141f3340d29e7c6181177d4e5e9483a9f7)
14
+ - Files: vendored under packages/babylon-ledger-vault-signer/src/vendor/ledger-bitcoin/
15
+ (source-in-tree; not yet reachable from the published bundle)
16
+ - License: Apache License 2.0
17
+ - Modifications: see the per-file provenance headers in the vendored source
18
+ (explicit Buffer import, defensive strict-null guards, formatting; psbtv2.ts
19
+ additionally drops `fromBitcoinJS` and unifies the serialization key
20
+ comparator to byte-lexicographic order).
21
+
22
+ ### Apache License 2.0
23
+
24
+ Apache License
25
+ Version 2.0, January 2004
26
+ http://www.apache.org/licenses/
27
+
28
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
29
+
30
+ 1. Definitions.
31
+
32
+ "License" shall mean the terms and conditions for use, reproduction,
33
+ and distribution as defined by Sections 1 through 9 of this document.
34
+
35
+ "Licensor" shall mean the copyright owner or entity authorized by
36
+ the copyright owner that is granting the License.
37
+
38
+ "Legal Entity" shall mean the union of the acting entity and all
39
+ other entities that control, are controlled by, or are under common
40
+ control with that entity. For the purposes of this definition,
41
+ "control" means (i) the power, direct or indirect, to cause the
42
+ direction or management of such entity, whether by contract or
43
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
44
+ outstanding shares, or (iii) beneficial ownership of such entity.
45
+
46
+ "You" (or "Your") shall mean an individual or Legal Entity
47
+ exercising permissions granted by this License.
48
+
49
+ "Source" form shall mean the preferred form for making modifications,
50
+ including but not limited to software source code, documentation
51
+ source, and configuration files.
52
+
53
+ "Object" form shall mean any form resulting from mechanical
54
+ transformation or translation of a Source form, including but
55
+ not limited to compiled object code, generated documentation,
56
+ and conversions to other media types.
57
+
58
+ "Work" shall mean the work of authorship, whether in Source or
59
+ Object form, made available under the License, as indicated by a
60
+ copyright notice that is included in or attached to the work
61
+ (an example is provided in the Appendix below).
62
+
63
+ "Derivative Works" shall mean any work, whether in Source or Object
64
+ form, that is based on (or derived from) the Work and for which the
65
+ editorial revisions, annotations, elaborations, or other modifications
66
+ represent, as a whole, an original work of authorship. For the purposes
67
+ of this License, Derivative Works shall not include works that remain
68
+ separable from, or merely link (or bind by name) to the interfaces of,
69
+ the Work and Derivative Works thereof.
70
+
71
+ "Contribution" shall mean any work of authorship, including
72
+ the original version of the Work and any modifications or additions
73
+ to that Work or Derivative Works thereof, that is intentionally
74
+ submitted to Licensor for inclusion in the Work by the copyright owner
75
+ or by an individual or Legal Entity authorized to submit on behalf of
76
+ the copyright owner. For the purposes of this definition, "submitted"
77
+ means any form of electronic, verbal, or written communication sent
78
+ to the Licensor or its representatives, including but not limited to
79
+ communication on electronic mailing lists, source code control systems,
80
+ and issue tracking systems that are managed by, or on behalf of, the
81
+ Licensor for the purpose of discussing and improving the Work, but
82
+ excluding communication that is conspicuously marked or otherwise
83
+ designated in writing by the copyright owner as "Not a Contribution."
84
+
85
+ "Contributor" shall mean Licensor and any individual or Legal Entity
86
+ on behalf of whom a Contribution has been received by Licensor and
87
+ subsequently incorporated within the Work.
88
+
89
+ 2. Grant of Copyright License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ copyright license to reproduce, prepare Derivative Works of,
93
+ publicly display, publicly perform, sublicense, and distribute the
94
+ Work and such Derivative Works in Source or Object form.
95
+
96
+ 3. Grant of Patent License. Subject to the terms and conditions of
97
+ this License, each Contributor hereby grants to You a perpetual,
98
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
99
+ (except as stated in this section) patent license to make, have made,
100
+ use, offer to sell, sell, import, and otherwise transfer the Work,
101
+ where such license applies only to those patent claims licensable
102
+ by such Contributor that are necessarily infringed by their
103
+ Contribution(s) alone or by combination of their Contribution(s)
104
+ with the Work to which such Contribution(s) was submitted. If You
105
+ institute patent litigation against any entity (including a
106
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
107
+ or a Contribution incorporated within the Work constitutes direct
108
+ or contributory patent infringement, then any patent licenses
109
+ granted to You under this License for that Work shall terminate
110
+ as of the date such litigation is filed.
111
+
112
+ 4. Redistribution. You may reproduce and distribute copies of the
113
+ Work or Derivative Works thereof in any medium, with or without
114
+ modifications, and in Source or Object form, provided that You
115
+ meet the following conditions:
116
+
117
+ (a) You must give any other recipients of the Work or
118
+ Derivative Works a copy of this License; and
119
+
120
+ (b) You must cause any modified files to carry prominent notices
121
+ stating that You changed the files; and
122
+
123
+ (c) You must retain, in the Source form of any Derivative Works
124
+ that You distribute, all copyright, patent, trademark, and
125
+ attribution notices from the Source form of the Work,
126
+ excluding those notices that do not pertain to any part of
127
+ the Derivative Works; and
128
+
129
+ (d) If the Work includes a "NOTICE" text file as part of its
130
+ distribution, then any Derivative Works that You distribute must
131
+ include a readable copy of the attribution notices contained
132
+ within such NOTICE file, excluding those notices that do not
133
+ pertain to any part of the Derivative Works, in at least one
134
+ of the following places: within a NOTICE text file distributed
135
+ as part of the Derivative Works; within the Source form or
136
+ documentation, if provided along with the Derivative Works; or,
137
+ within a display generated by the Derivative Works, if and
138
+ wherever such third-party notices normally appear. The contents
139
+ of the NOTICE file are for informational purposes only and
140
+ do not modify the License. You may add Your own attribution
141
+ notices within Derivative Works that You distribute, alongside
142
+ or as an addendum to the NOTICE text from the Work, provided
143
+ that such additional attribution notices cannot be construed
144
+ as modifying the License.
145
+
146
+ You may add Your own copyright statement to Your modifications and
147
+ may provide additional or different license terms and conditions
148
+ for use, reproduction, or distribution of Your modifications, or
149
+ for any such Derivative Works as a whole, provided Your use,
150
+ reproduction, and distribution of the Work otherwise complies with
151
+ the conditions stated in this License.
152
+
153
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
154
+ any Contribution intentionally submitted for inclusion in the Work
155
+ by You to the Licensor shall be under the terms and conditions of
156
+ this License, without any additional terms or conditions.
157
+ Notwithstanding the above, nothing herein shall supersede or modify
158
+ the terms of any separate license agreement you may have executed
159
+ with Licensor regarding such Contributions.
160
+
161
+ 6. Trademarks. This License does not grant permission to use the trade
162
+ names, trademarks, service marks, or product names of the Licensor,
163
+ except as required for reasonable and customary use in describing the
164
+ origin of the Work and reproducing the content of the NOTICE file.
165
+
166
+ 7. Disclaimer of Warranty. Unless required by applicable law or
167
+ agreed to in writing, Licensor provides the Work (and each
168
+ Contributor provides its Contributions) on an "AS IS" BASIS,
169
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
170
+ implied, including, without limitation, any warranties or conditions
171
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
172
+ PARTICULAR PURPOSE. You are solely responsible for determining the
173
+ appropriateness of using or redistributing the Work and assume any
174
+ risks associated with Your exercise of permissions under this License.
175
+
176
+ 8. Limitation of Liability. In no event and under no legal theory,
177
+ whether in tort (including negligence), contract, or otherwise,
178
+ unless required by applicable law (such as deliberate and grossly
179
+ negligent acts) or agreed to in writing, shall any Contributor be
180
+ liable to You for damages, including any direct, indirect, special,
181
+ incidental, or consequential damages of any character arising as a
182
+ result of this License or out of the use or inability to use the
183
+ Work (including but not limited to damages for loss of goodwill,
184
+ work stoppage, computer failure or malfunction, or any and all
185
+ other commercial damages or losses), even if such Contributor
186
+ has been advised of the possibility of such damages.
187
+
188
+ 9. Accepting Warranty or Additional Liability. While redistributing
189
+ the Work or Derivative Works thereof, You may choose to offer,
190
+ and charge a fee for, acceptance of support, warranty, indemnity,
191
+ or other liability obligations and/or rights consistent with this
192
+ License. However, in accepting such obligations, You may act only
193
+ on Your own behalf and on Your sole responsibility, not on behalf
194
+ of any other Contributor, and only if You agree to indemnify,
195
+ defend, and hold each Contributor harmless for any liability
196
+ incurred by, or claims asserted against, such Contributor by reason
197
+ of your accepting any such warranty or additional liability.
198
+
199
+ END OF TERMS AND CONDITIONS
200
+
201
+ APPENDIX: How to apply the Apache License to your work.
202
+
203
+ To apply the Apache License to your work, attach the following
204
+ boilerplate notice, with the fields enclosed by brackets "{}"
205
+ replaced with your own identifying information. (Don't include
206
+ the brackets!) The text should be enclosed in the appropriate
207
+ comment syntax for the file format. We also recommend that a
208
+ file or class name and description of purpose be included on the
209
+ same "printed page" as the copyright notice for easier
210
+ identification within third-party archives.
211
+
212
+ Copyright {yyyy} {name of copyright owner}
213
+
214
+ Licensed under the Apache License, Version 2.0 (the "License");
215
+ you may not use this file except in compliance with the License.
216
+ You may obtain a copy of the License at
217
+
218
+ http://www.apache.org/licenses/LICENSE-2.0
219
+
220
+ Unless required by applicable law or agreed to in writing, software
221
+ distributed under the License is distributed on an "AS IS" BASIS,
222
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
223
+ See the License for the specific language governing permissions and
224
+ limitations under the License.
@@ -0,0 +1,15 @@
1
+ import { ApduSender } from './vaultCommands';
2
+ /**
3
+ * Read the x-only public key at the given BIP-32 path.
4
+ *
5
+ * @param send - APDU sender bound to the live device session
6
+ * @param path - Full BIP-32 path as raw u32 levels (hardened bits included)
7
+ * @param bip32Versions - Version bytes for the decode: the signet build
8
+ * returns a tpub, and `@scure/bip32` throws "Version mismatch" on its
9
+ * mainnet defaults without them.
10
+ */
11
+ export declare function getXOnlyPublicKeyHex(send: ApduSender, path: readonly number[], bip32Versions: {
12
+ private: number;
13
+ public: number;
14
+ }): Promise<string>;
15
+ //# sourceMappingURL=derivation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derivation.d.ts","sourceRoot":"","sources":["../src/derivation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAAW,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAoB3D;;;;;;;;GAQG;AACH,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,aAAa,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACjD,OAAO,CAAC,MAAM,CAAC,CAkBjB"}
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Ledger vault-app intent caps, mirrored from the firmware
3
+ * (`app-babylon-vault` @ `8f99b8b`: `vault_tlv.c`, `vault_intent.h`,
4
+ * `vault_constants.h`). The device rejects violations with SW_INCORRECT_DATA
5
+ * and a dead session, so we fail comprehensibly BEFORE the ceremony.
6
+ *
7
+ * These are device-envelope limits only — none exist on-chain or in
8
+ * btc-vault. They live in this signer package; the SDK must never learn them.
9
+ *
10
+ * @module ledger-vault-signer/deviceCaps
11
+ */
12
+ /**
13
+ * Keeper and universal-challenger counts, each `[1, 32]` (`vault_intent.h:8-9`,
14
+ * checked `vault_tlv.c:130,137`). Far below the protocol: the contract allows
15
+ * 1500 universal challengers and sets no keeper cap at all.
16
+ */
17
+ export declare const DEVICE_MAX_PARTICIPANTS_PER_ROLE = 32;
18
+ /**
19
+ * Vault groups per intent (`vault_constants.h` VAULT_MAX_VAULTS). Multi-vault
20
+ * PegIn signing works in one session — `_validate_pegin` auto-detects the
21
+ * group from Input 0's PSBT_IN_OUTPUT_INDEX.
22
+ */
23
+ export declare const DEVICE_MAX_VAULTS_PER_INTENT = 10;
24
+ /**
25
+ * Fee-rate bounds (sat/vB): the intent parser rejects rate == 0 AND
26
+ * rate > UINT32_MAX (`vault_tlv.c:73`), so the `>= 1` floor is both a device
27
+ * check and the contract invariant.
28
+ */
29
+ export declare const DEVICE_MAX_BASE_FEE_RATE_SAT_PER_VB = 4294967295n;
30
+ /** Shared lower bound for the CSV/refund timelocks (`vault_constants.h:100`). */
31
+ export declare const DEVICE_TIMELOCK_MIN_BLOCKS = 72;
32
+ /** Inclusive upper bound for `pegin_csv_timelock` (`vault_constants.h:103`). */
33
+ export declare const DEVICE_PEGIN_CSV_TIMELOCK_MAX_BLOCKS = 1008;
34
+ /** Inclusive upper bound for `htlc_refund_timelock` (`vault_constants.h:106`). */
35
+ export declare const DEVICE_REFUND_TIMELOCK_MAX_BLOCKS = 4320;
36
+ /**
37
+ * Inclusive bounds for `payout_timelock`. The intent parser is EXCLUSIVE
38
+ * `(90, 4032)` (`vault_tlv.c`), so the accepted range is `[91, 4031]`; the
39
+ * exclusive form gates deposits, so it wins over Screen 8's inclusive form.
40
+ */
41
+ export declare const DEVICE_PAYOUT_TIMELOCK_MIN_BLOCKS = 91;
42
+ export declare const DEVICE_PAYOUT_TIMELOCK_MAX_BLOCKS = 4031;
43
+ /**
44
+ * Relay dust limit for per-vault commission and reclaim values
45
+ * (`vault_constants.h`). Equal to btc-vault's `DUST_AMOUNT` by value but a
46
+ * distinct role — never merge them.
47
+ */
48
+ export declare const DEVICE_VAULT_DUST_LIMIT_SATS = 546n;
49
+ /**
50
+ * Device-only floor on `depositorClaimValue` — btc-vault's own floor is 330,
51
+ * so `[330, 545]` is allowed by the protocol but not the device. Firmware
52
+ * asymmetry; must not be "fixed" on the protocol side.
53
+ */
54
+ export declare const DEVICE_MIN_DEPOSITOR_CLAIM_VALUE_SATS = 546n;
55
+ /**
56
+ * The device's `peginAmount > commissionFee + 2 * dust` check. No btc-vault
57
+ * counterpart — firmware-only; mirrored to fail early, never to be ported
58
+ * into the protocol.
59
+ */
60
+ export declare const DEVICE_PEGIN_AMOUNT_DUST_MULTIPLE = 2n;
61
+ /**
62
+ * The ONLY tx-graph version this firmware can complete. The intent TLV
63
+ * carries no core-version field, so the device cannot reject a mismatched
64
+ * graph at load — the intent approves on-screen and signing fails at PSBT
65
+ * time. Any other version (v1 or a future v3) must be refused before device
66
+ * I/O, hence an exact match, not a floor.
67
+ */
68
+ export declare const DEVICE_SUPPORTED_VAULT_CORE_VERSION = 2;
69
+ //# sourceMappingURL=deviceCaps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deviceCaps.d.ts","sourceRoot":"","sources":["../src/deviceCaps.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,KAAK,CAAC;AAEnD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,mCAAmC,cAAc,CAAC;AAE/D,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,KAAK,CAAC;AAE7C,gFAAgF;AAChF,eAAO,MAAM,oCAAoC,OAAO,CAAC;AAEzD,kFAAkF;AAClF,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAEjD;;;;GAIG;AACH,eAAO,MAAM,qCAAqC,OAA+B,CAAC;AAElF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC;AAEpD;;;;;;GAMG;AACH,eAAO,MAAM,mCAAmC,IAAI,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { DmkSessionHandle } from './dmkSession';
2
+ import { ApduSender } from './vaultCommands';
3
+ /**
4
+ * Build a sender bound to one device session. A `sessionId` must never outlive
5
+ * its connection — recreate the sender whenever the session changes.
6
+ */
7
+ export declare function createDmkApduSender(handle: DmkSessionHandle): ApduSender;
8
+ //# sourceMappingURL=dmkApduSender.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dmkApduSender.d.ts","sourceRoot":"","sources":["../src/dmkApduSender.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAkFlD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,UAAU,CA4CxE"}
@@ -0,0 +1,35 @@
1
+ import { DeviceManagementKit, DeviceSessionId } from '@ledgerhq/device-management-kit';
2
+ export interface DmkSessionHandle {
3
+ readonly dmk: DeviceManagementKit;
4
+ readonly sessionId: DeviceSessionId;
5
+ /**
6
+ * App name/version at connect time ("BOLOS" = dashboard). Diagnostic only;
7
+ * absent when the preflight failed. Never re-read between intent phases.
8
+ */
9
+ readonly appName?: string;
10
+ readonly appVersion?: string;
11
+ }
12
+ /**
13
+ * Discover and connect to a device, returning a handle for further commands.
14
+ *
15
+ * MUST be called from a user gesture: WebHID is Chromium-only, needs a secure
16
+ * context, and its picker fails silently otherwise.
17
+ *
18
+ * @throws If no device is selected or the connection fails
19
+ */
20
+ export declare function connectDmkSession(): Promise<DmkSessionHandle>;
21
+ /**
22
+ * True while the session is usable (dead sessions must be rebuilt from
23
+ * discovery). The signal is the `DeviceSessionNotFound` THROW — DMK never
24
+ * emits a "NOT CONNECTED" state. A just-unplugged device may briefly report
25
+ * alive; the first ceremony APDU then rejects loudly.
26
+ */
27
+ export declare function isSessionAlive(handle: DmkSessionHandle): Promise<boolean>;
28
+ /** Disconnect the session; safe to call when already disconnected. */
29
+ export declare function disconnectDmkSession(handle: DmkSessionHandle): Promise<void>;
30
+ /**
31
+ * Tear down the singleton. Only for app shutdown or tests; a provider
32
+ * disconnect should use {@link disconnectDmkSession} and leave the DMK up.
33
+ */
34
+ export declare function closeDmk(): void;
35
+ //# sourceMappingURL=dmkSession.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dmkSession.d.ts","sourceRoot":"","sources":["../src/dmkSession.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAoB,MAAM,iCAAiC,CAAC;AAU9G,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAuCD;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAkBnE;AAuBD;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAU/E;AAED,sEAAsE;AACtE,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMlF;AAED;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,IAAI,CAI/B"}
@@ -0,0 +1,8 @@
1
+ import { DepositTerms } from './types';
2
+ /**
3
+ * Assert the terms lie inside the device's accepted intent domain.
4
+ *
5
+ * @throws {DepositTermsRejectedError} on the first violation
6
+ */
7
+ export declare function assertDepositTermsDeviceCompatible(terms: DepositTerms): void;
8
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAgBH,OAAO,EAA6B,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AAUvE;;;;GAIG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAsI5E"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Typed errors for device outcomes the consuming adapter must classify.
3
+ * This package deliberately has no dependency on wallet-connector's
4
+ * WalletError taxonomy — the adapter maps these at the seam. Matching is
5
+ * by `name`, mirroring the DepositTermsRejectedError contract, so the
6
+ * classification survives duplicated module instances.
7
+ *
8
+ * @module ledger-vault-signer/errors
9
+ */
10
+ export declare const LEDGER_USER_REFUSED_ERROR_NAME = "LedgerUserRefusedError";
11
+ export declare const LEDGER_DEVICE_LOCKED_ERROR_NAME = "LedgerDeviceLockedError";
12
+ export declare const LEDGER_DEVICE_ERROR_NAME = "LedgerDeviceError";
13
+ /**
14
+ * The user declined the request on-device. The message keeps the
15
+ * "User rejected" prefix — wallet-connector's `isUserRejectionMessage` and
16
+ * the vault app's user-cancellation classifier match on it when a wrapper
17
+ * drops the typed error.
18
+ */
19
+ export declare class LedgerUserRefusedError extends Error {
20
+ readonly statusWord: number;
21
+ constructor(statusWord: number);
22
+ }
23
+ /** The device is locked; the request never reached the app. */
24
+ export declare class LedgerDeviceLockedError extends Error {
25
+ readonly statusWord: number;
26
+ constructor(statusWord: number);
27
+ }
28
+ /**
29
+ * Any other non-OK status word: the device rejected the request for a reason
30
+ * the sender does not classify further. Carries the status word as data; the
31
+ * message already names the instruction and mapped meaning.
32
+ */
33
+ export declare class LedgerDeviceError extends Error {
34
+ readonly statusWord: number;
35
+ constructor(statusWord: number, message: string);
36
+ }
37
+ export declare function isLedgerUserRefusedError(error: unknown): error is LedgerUserRefusedError;
38
+ export declare function isLedgerDeviceError(error: unknown): error is LedgerDeviceError;
39
+ export declare function isLedgerDeviceLockedError(error: unknown): error is LedgerDeviceLockedError;
40
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,8BAA8B,2BAA2B,CAAC;AACvE,eAAO,MAAM,+BAA+B,4BAA4B,CAAC;AACzE,eAAO,MAAM,wBAAwB,sBAAsB,CAAC;AAM5D;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED,+DAA+D;AAC/D,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAKhD;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,sBAAsB,CAExF;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAE9E;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F"}
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var le=Object.create;var O=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var Te=(e,t,n)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var fe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of de(t))!pe.call(e,o)&&o!==n&&O(e,o,{get:()=>t[o],enumerable:!(r=_e(t,o))||r.enumerable});return e};var d=(e,t,n)=>(n=e!=null?le(he(e)):{},fe(t||!e||!e.__esModule?O(n,"default",{value:e,enumerable:!0}):n,e));var w=(e,t,n)=>Te(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ge=require("@scure/bip32"),Ae=1,me=1,Re=1,we=2,Ce=33,Se=256,Pe=257,$e=258,De=39,Ie=259,ve=105,Oe=260,Le=261,Ve=262,ye=271,Ue=265,Ne=266,Me=267,ke=268,be=269,Ge=270,Fe=263,xe=264,D=32,Be=32,S=255,Ke=3+D,b=Math.floor(S/Ke);function _(e,t){if(t.length>S)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function v(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let i=t-1;i>=0;i--)r[i]=Number(o&0xffn),o>>=8n;return r}function T(e,t,n){return _(e,v(BigInt(t),1,n))}function $(e,t,n){return _(e,v(BigInt(t),4,n))}function g(e,t,n){return _(e,v(t,8,n))}function I(e){const t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function U(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const G=5;function te(e){if(e.depositorPath.length!==G)throw new Error(`depositorPath must have exactly ${G} levels, got ${e.depositorPath.length}`);const t=I(e.depositorPath.map(n=>v(BigInt(n>>>0),4,"path level")));return I([T(Re,Ae,"structureType"),T(we,me,"version"),$(Ce,e.coinType,"coinType"),g(Se,e.baseFeeRate,"baseFeeRate"),$(Pe,e.peginCsvTimelock,"peginCsvTimelock"),$($e,e.payoutTimelock,"payoutTimelock"),_(De,U(e.prepeginTxidInternal,Be,"prepeginTxid")),$(Ie,e.htlcRefundTimelock,"htlcRefundTimelock"),_(ve,t),T(Oe,e.keeperCount,"keeperCount"),T(Le,e.challengerCount,"challengerCount"),T(Ve,e.vaultCount,"vaultCount"),g(ye,e.prepeginMaxFee,"prepeginMaxFee")])}function ne(e){return I([T(Ue,e.htlcVout,"htlcVout"),_(Ne,U(e.vaultProviderPubkey,D,"vaultProviderPubkey")),g(Me,e.vaultAmount,"vaultAmount"),g(ke,e.commissionFee,"commissionFee"),g(be,e.depositorClaimValue,"depositorClaimValue"),g(Ge,e.peginMaxFee,"peginMaxFee")])}function oe(e,t){const n=(i,u)=>i.map((s,E)=>U(s,D,`${u}[${E}]`)).sort((s,E)=>{for(let l=0;l<D;l++)if(s[l]!==E[l])return s[l]-E[l];return 0}),r=[...n(e,"keeper").map(i=>_(Fe,i)),...n(t,"challenger").map(i=>_(xe,i))],o=[];for(let i=0;i<r.length;i+=b)o.push(I(r.slice(i,i+b)));return o}const m=225,L=128,F=129,He=0,Ye=1,Xe=0,je=1,We=2,P=0,x=64,B=1024,K=10,H=32;function qe(e){return new Uint8Array([e>>8&255,e&255])}function Je(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function V(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const Y=/^[a-z0-9-]+$/;async function ze(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>x)throw new Error(`appName must be 1..${x} bytes, got ${o.length}`);if(!Y.test(t))throw new Error(`appName must match ${Y} — the device rejects other characters`);if(n.length<1||n.length>K)throw new Error(`derivationPath must have 1..${K} levels`);if(r.length<1||r.length>B)throw new Error(`context must be 1..${B} bytes, got ${r.length}`);const i=V([new Uint8Array([o.length]),o,new Uint8Array([n.length]),V(n.map(Je)),qe(r.length)]),u=Math.min(r.length,S-i.length);if(u<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let s=await e({cla:m,ins:F,p1:He,p2:P,data:V([i,r.subarray(0,u)])});for(let E=u;E<r.length;E+=S)s=await e({cla:m,ins:F,p1:Ye,p2:P,data:r.subarray(E,E+S)});if(s.length!==H)throw new Error(`Expected a ${H}-byte context root, got ${s.length} bytes`);return s}async function Qe(e,{scalars:t,groups:n,keeperPubkeys:r,challengerPubkeys:o}){if(n.length!==t.vaultCount)throw new Error(`vaultCount ${t.vaultCount} does not match ${n.length} group(s)`);if(r.length!==t.keeperCount)throw new Error(`keeperCount ${t.keeperCount} does not match ${r.length} key(s)`);if(t.keeperCount<1||t.challengerCount<1)throw new Error(`Both rosters must be non-empty: keeperCount=${t.keeperCount}, challengerCount=${t.challengerCount}`);if(o.length!==t.challengerCount)throw new Error(`challengerCount ${t.challengerCount} does not match ${o.length} key(s)`);await e({cla:m,ins:L,p1:Xe,p2:P,data:te(t)});for(const i of n)await e({cla:m,ins:L,p1:je,p2:P,data:ne(i)});for(const i of oe(r,o))await e({cla:m,ins:L,p1:We,p2:P,data:i})}const Ze=0,et=0,tt=1,nt=0,X=33,j=10;async function ot(e,t,n){if(t.length<1||t.length>j)throw new Error(`BIP-32 path must have 1..${j} levels, got ${t.length}`);const r=await e({cla:m,ins:Ze,p1:et,p2:tt,data:st(t)}),o=new TextDecoder().decode(r),i=ge.HDKey.fromExtendedKey(o,n);if(!i.publicKey||i.publicKey.length!==X)throw new Error(`Ledger returned an extended key without a ${X}-byte public key`);return rt(i.publicKey.subarray(1))}function rt(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function st(e){const t=new Uint8Array(2+e.length*4);return t[0]=nt,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const N="LedgerUserRefusedError",M="LedgerDeviceLockedError",k="LedgerDeviceError";function re(e){return e.toString(16).padStart(4,"0")}class se extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${re(n)})`);w(this,"statusWord");this.name=N,this.statusWord=n}}class ie extends Error{constructor(n){super(`The Ledger device is locked — unlock it and retry (0x${re(n)})`);w(this,"statusWord");this.name=M,this.statusWord=n}}class ce extends Error{constructor(n,r){super(r);w(this,"statusWord");this.name=k,this.statusWord=n}}function it(e){return e instanceof Error&&e.name===N}function ct(e){return e instanceof Error&&e.name===k}function at(e){return e instanceof Error&&e.name===M}const ut=36864,Et=new Set([21761,27013]),lt=new Set([21781,27010,21251]),W=2,ae=28160,_t={27264:"The device rejected the data as invalid",27266:"The device does not support this request — check that the app build matches the selected network",27270:"The device rejected the instruction parameters",27271:"The device rejected the payload length",27904:"The running app does not support this instruction",[ae]:"The running app does not handle vault instructions — open the Babylon Vault app",45056:"The device reported a wrong response length",45063:"The device is not in the expected state for this step",45064:"The device rejected a signature or HMAC as invalid",45065:"The device rejected the CPFP anchor",45066:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function dt(e){if(e.statusCode.length!==W)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${W}.`);return e.statusCode[0]<<8|e.statusCode[1]}function ht(e){if(e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function q(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function h(e){return e.toString(16).padStart(2,"0")}function J(e){return e.toString(16).padStart(4,"0")}function pt(e){return async t=>{const n=`${h(t.cla)} ${h(t.ins)} ${h(t.p1)} ${h(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:ht(t)})}catch(i){throw q()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,i),i}const o=dt(r);if(q()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${J(o)} len=${r.data.length}`),Et.has(o))throw new se(o);if(lt.has(o))throw new ie(o);if(o!==ut){const i=_t[o],u=o===ae&&e.appName?` (app at connect time: "${e.appName}"${e.appVersion?` v${e.appVersion}`:""})`:"";throw new ce(o,`${i??"The device rejected the request"} (ins 0x${h(t.ins)} p1 0x${h(t.p1)}, sw 0x${J(o)})${u}`)}return r.data}}const Tt={isRefresherDisabled:!0};let A,f;function ft(){if(!f){const e=(async()=>{const[{DeviceManagementKitBuilder:t},{webHidTransportFactory:n}]=await Promise.all([import("@ledgerhq/device-management-kit"),import("@ledgerhq/device-transport-kit-web-hid")]);return A=new t().addTransport(n).build(),A})().catch(t=>{throw f===e&&(f=void 0),t});f=e}return f}async function gt(){const e=await ft(),[{firstValueFrom:t},{webHidIdentifier:n}]=await Promise.all([import("rxjs"),import("@ledgerhq/device-transport-kit-web-hid")]),r=await t(e.startDiscovering({transport:n})),o=await e.connect({device:r,sessionRefresherOptions:Tt}),i=await At(e,o);return{dmk:e,sessionId:o,...i}}async function At(e,t){try{const{GetAppAndVersionCommand:n,isSuccessCommandResult:r}=await import("@ledgerhq/device-management-kit"),o=await e.sendCommand({sessionId:t,command:new n});return r(o)?{appName:o.data.name,appVersion:o.data.version}:{}}catch{return{}}}async function mt(e){const{firstValueFrom:t}=await import("rxjs");try{return await t(e.dmk.getDeviceSessionState({sessionId:e.sessionId})),!0}catch(n){if((n==null?void 0:n._tag)==="DeviceSessionNotFound")return!1;throw n}}async function Rt(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function wt(){A==null||A.close(),A=void 0,f=void 0}const z=32,Ct=10,Q=0xffffffffn,Z=72,St=1008,Pt=4320,$t=91,Dt=4031,ue=546n,ee=ue,It=2n,y=2,Ee="DepositTermsRejectedError";class c extends Error{constructor(n,r="device-envelope"){super(n);w(this,"reason");this.name=Ee,this.reason=r}}const a="Deposit terms outside the device-supported range";function p(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new c(`${a}: ${e} ${t} not in [${n}, ${r}]`)}function vt(e){if(e.vaultCoreVersion!==y)throw new c(`${a}: vaultCoreVersion ${e.vaultCoreVersion} is not ${y}; this device only supports tx-graph v${y} deposits.`);if(e.protocolFeeRate<1n||e.protocolFeeRate>Q)throw new c(`${a}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Q}]`);if(p("timelockPegin",e.timelockPegin,Z,St),p("timelockAssert",e.timelockAssert,$t,Dt),p("timelockRefund",e.timelockRefund,Z,Pt),p("keeper count",e.vaultKeeperBtcPubkeys.length,1,z),p("challenger count",e.universalChallengerBtcPubkeys.length,1,z),p("vault count",e.vaults.length,1,Ct),C("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n)throw new c(`${a}: prepeginMaxFee ${e.prepeginMaxFee} must be >= 1`);let t=-1;for(const s of e.vaults){if(!Number.isInteger(s.htlcVout)||s.htlcVout<0||s.htlcVout>255)throw new c(`${a}: htlcVout ${s.htlcVout} not in [0, 255]`);if(s.htlcVout<=t)throw new c(`${a}: vault groups must be in strictly ascending htlcVout order; got ${s.htlcVout} after ${t}`);t=s.htlcVout}const n=s=>s.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(s=>n(s.vaultProviderBtcPubkey))),o=new Set;for(const[s,E]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of E){const R=n(l);if(r.has(R))throw new c(`${a}: ${s} contains the vault provider's own key (${R.slice(0,16)}…)`);if(o.has(R))throw new c(`${a}: duplicate participant key in ${s} (${R.slice(0,16)}…)`);o.add(R)}const i=ue,u=It*i;for(const s of e.vaults){if(C(`vault ${s.htlcVout} peginAmount`,s.peginAmount),C(`vault ${s.htlcVout} commissionFee`,s.commissionFee),C(`vault ${s.htlcVout} depositorClaimValue`,s.depositorClaimValue),C(`vault ${s.htlcVout} peginMaxFee`,s.peginMaxFee),s.commissionFee<i)throw new c(`${a}: vault ${s.htlcVout} commissionFee ${s.commissionFee} below the ${i}-sat dust limit`);if(s.depositorClaimValue<ee)throw new c(`${a}: vault ${s.htlcVout} depositorClaimValue ${s.depositorClaimValue} below the ${ee}-sat device floor`);if(s.peginAmount<=s.commissionFee+u)throw new c(`${a}: vault ${s.htlcVout} peginAmount ${s.peginAmount} must exceed commissionFee + ${u} (${s.commissionFee+u})`)}}const Ot=(1n<<64n)-1n;function C(e,t){if(t<0n||t>Ot)throw new c(`${a}: ${e} ${t} does not fit in an unsigned 64-bit field`)}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Ee;exports.DepositTermsRejectedError=c;exports.LEDGER_DEVICE_ERROR_NAME=k;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=M;exports.LEDGER_USER_REFUSED_ERROR_NAME=N;exports.LedgerDeviceError=ce;exports.LedgerDeviceLockedError=ie;exports.LedgerUserRefusedError=se;exports.approveVaultIntent=Qe;exports.assertDepositTermsDeviceCompatible=vt;exports.closeDmk=wt;exports.connectDmkSession=gt;exports.createDmkApduSender=pt;exports.deriveContextHash=ze;exports.disconnectDmkSession=Rt;exports.encodeIntentGroup=ne;exports.encodeIntentScalars=te;exports.encodeKeyBatches=oe;exports.getXOnlyPublicKeyHex=ot;exports.isLedgerDeviceError=ct;exports.isLedgerDeviceLockedError=at;exports.isLedgerUserRefusedError=it;exports.isSessionAlive=mt;
2
+ //# sourceMappingURL=index.cjs.map