@icp-sdk/core 4.2.3 → 5.0.0-beta.1

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 (474) hide show
  1. package/lib/cjs/agent/actor.d.ts +203 -0
  2. package/lib/cjs/agent/actor.d.ts.map +1 -0
  3. package/lib/cjs/agent/actor.js +341 -0
  4. package/lib/cjs/agent/actor.js.map +1 -0
  5. package/lib/cjs/agent/agent/api.d.ts +216 -0
  6. package/lib/cjs/agent/agent/api.d.ts.map +1 -0
  7. package/lib/cjs/agent/agent/api.js +39 -0
  8. package/lib/cjs/agent/agent/api.js.map +1 -0
  9. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts +37 -0
  10. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -0
  11. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js +51 -0
  12. package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -0
  13. package/lib/cjs/agent/agent/http/index.d.ts +190 -0
  14. package/lib/cjs/agent/agent/http/index.d.ts.map +1 -0
  15. package/lib/cjs/agent/agent/http/index.js +1159 -0
  16. package/lib/cjs/agent/agent/http/index.js.map +1 -0
  17. package/lib/cjs/agent/agent/http/transforms.d.ts +54 -0
  18. package/lib/cjs/agent/agent/http/transforms.d.ts.map +1 -0
  19. package/lib/cjs/agent/agent/http/transforms.js +135 -0
  20. package/lib/cjs/agent/agent/http/transforms.js.map +1 -0
  21. package/lib/cjs/agent/agent/http/types.d.ts +81 -0
  22. package/lib/cjs/agent/agent/http/types.d.ts.map +1 -0
  23. package/lib/cjs/agent/agent/http/types.js +43 -0
  24. package/lib/cjs/agent/agent/http/types.js.map +1 -0
  25. package/lib/cjs/agent/agent/index.d.ts +3 -0
  26. package/lib/cjs/agent/agent/index.d.ts.map +1 -0
  27. package/lib/cjs/agent/agent/index.js +19 -0
  28. package/lib/cjs/agent/agent/index.js.map +1 -0
  29. package/lib/cjs/agent/auth.d.ts +91 -0
  30. package/lib/cjs/agent/auth.d.ts.map +1 -0
  31. package/lib/cjs/agent/auth.js +65 -0
  32. package/lib/cjs/agent/auth.js.map +1 -0
  33. package/lib/cjs/agent/canisterStatus/index.d.ts +61 -0
  34. package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -0
  35. package/lib/cjs/agent/canisterStatus/index.js +239 -0
  36. package/lib/cjs/agent/canisterStatus/index.js.map +1 -0
  37. package/lib/cjs/agent/cbor.d.ts +26 -0
  38. package/lib/cjs/agent/cbor.d.ts.map +1 -0
  39. package/lib/cjs/agent/cbor.js +93 -0
  40. package/lib/cjs/agent/cbor.js.map +1 -0
  41. package/lib/cjs/agent/certificate.d.ts +286 -0
  42. package/lib/cjs/agent/certificate.d.ts.map +1 -0
  43. package/lib/cjs/agent/certificate.js +762 -0
  44. package/lib/cjs/agent/certificate.js.map +1 -0
  45. package/lib/cjs/agent/constants.d.ts +18 -0
  46. package/lib/cjs/agent/constants.d.ts.map +1 -0
  47. package/lib/cjs/agent/constants.js +22 -0
  48. package/lib/cjs/agent/constants.js.map +1 -0
  49. package/lib/cjs/agent/der.d.ts +34 -0
  50. package/lib/cjs/agent/der.d.ts.map +1 -0
  51. package/lib/cjs/agent/der.js +175 -0
  52. package/lib/cjs/agent/der.js.map +1 -0
  53. package/lib/cjs/agent/errors.d.ts +386 -0
  54. package/lib/cjs/agent/errors.d.ts.map +1 -0
  55. package/lib/cjs/agent/errors.js +745 -0
  56. package/lib/cjs/agent/errors.js.map +1 -0
  57. package/lib/cjs/agent/fetch_candid.d.ts +9 -0
  58. package/lib/cjs/agent/fetch_candid.d.ts.map +1 -0
  59. package/lib/cjs/agent/fetch_candid.js +69 -0
  60. package/lib/cjs/agent/fetch_candid.js.map +1 -0
  61. package/lib/cjs/agent/index.d.ts +125 -1
  62. package/lib/cjs/agent/index.d.ts.map +1 -1
  63. package/lib/cjs/agent/index.js +142 -1
  64. package/lib/cjs/agent/index.js.map +1 -1
  65. package/lib/cjs/agent/observable.d.ts +24 -0
  66. package/lib/cjs/agent/observable.d.ts.map +1 -0
  67. package/lib/cjs/agent/observable.js +34 -0
  68. package/lib/cjs/agent/observable.js.map +1 -0
  69. package/lib/cjs/agent/polling/backoff.d.ts +50 -0
  70. package/lib/cjs/agent/polling/backoff.d.ts.map +1 -0
  71. package/lib/cjs/agent/polling/backoff.js +90 -0
  72. package/lib/cjs/agent/polling/backoff.js.map +1 -0
  73. package/lib/cjs/agent/polling/index.d.ts +63 -0
  74. package/lib/cjs/agent/polling/index.d.ts.map +1 -0
  75. package/lib/cjs/agent/polling/index.js +183 -0
  76. package/lib/cjs/agent/polling/index.js.map +1 -0
  77. package/lib/cjs/agent/polling/strategy.d.ts +52 -0
  78. package/lib/cjs/agent/polling/strategy.d.ts.map +1 -0
  79. package/lib/cjs/agent/polling/strategy.js +104 -0
  80. package/lib/cjs/agent/polling/strategy.js.map +1 -0
  81. package/lib/cjs/agent/public_key.d.ts +16 -0
  82. package/lib/cjs/agent/public_key.d.ts.map +1 -0
  83. package/lib/cjs/agent/public_key.js +52 -0
  84. package/lib/cjs/agent/public_key.js.map +1 -0
  85. package/lib/cjs/agent/request_id.d.ts +24 -0
  86. package/lib/cjs/agent/request_id.d.ts.map +1 -0
  87. package/lib/cjs/agent/request_id.js +88 -0
  88. package/lib/cjs/agent/request_id.js.map +1 -0
  89. package/lib/cjs/agent/subnetStatus/index.d.ts +70 -0
  90. package/lib/cjs/agent/subnetStatus/index.d.ts.map +1 -0
  91. package/lib/cjs/agent/subnetStatus/index.js +224 -0
  92. package/lib/cjs/agent/subnetStatus/index.js.map +1 -0
  93. package/lib/cjs/agent/utils/bls.d.ts +10 -0
  94. package/lib/cjs/agent/utils/bls.d.ts.map +1 -0
  95. package/lib/cjs/agent/utils/bls.js +20 -0
  96. package/lib/cjs/agent/utils/bls.js.map +1 -0
  97. package/lib/cjs/agent/utils/buffer.d.ts +22 -0
  98. package/lib/cjs/agent/utils/buffer.d.ts.map +1 -0
  99. package/lib/cjs/agent/utils/buffer.js +55 -0
  100. package/lib/cjs/agent/utils/buffer.js.map +1 -0
  101. package/lib/cjs/agent/utils/expirableMap.d.ts +80 -0
  102. package/lib/cjs/agent/utils/expirableMap.d.ts.map +1 -0
  103. package/lib/cjs/agent/utils/expirableMap.js +148 -0
  104. package/lib/cjs/agent/utils/expirableMap.js.map +1 -0
  105. package/lib/cjs/agent/utils/leb.d.ts +3 -0
  106. package/lib/cjs/agent/utils/leb.d.ts.map +1 -0
  107. package/lib/cjs/agent/utils/leb.js +17 -0
  108. package/lib/cjs/agent/utils/leb.js.map +1 -0
  109. package/lib/cjs/agent/utils/random.d.ts +6 -0
  110. package/lib/cjs/agent/utils/random.d.ts.map +1 -0
  111. package/lib/cjs/agent/utils/random.js +29 -0
  112. package/lib/cjs/agent/utils/random.js.map +1 -0
  113. package/lib/cjs/agent/utils/readState.d.ts +84 -0
  114. package/lib/cjs/agent/utils/readState.d.ts.map +1 -0
  115. package/lib/cjs/agent/utils/readState.js +149 -0
  116. package/lib/cjs/agent/utils/readState.js.map +1 -0
  117. package/lib/cjs/candid/candid-core.d.ts +72 -0
  118. package/lib/cjs/candid/candid-core.d.ts.map +1 -0
  119. package/lib/cjs/candid/candid-core.js +251 -0
  120. package/lib/cjs/candid/candid-core.js.map +1 -0
  121. package/lib/cjs/candid/candid-ui.d.ts +35 -0
  122. package/lib/cjs/candid/candid-ui.d.ts.map +1 -0
  123. package/lib/cjs/candid/candid-ui.js +317 -0
  124. package/lib/cjs/candid/candid-ui.js.map +1 -0
  125. package/lib/cjs/candid/idl.d.ts +579 -0
  126. package/lib/cjs/candid/idl.d.ts.map +1 -0
  127. package/lib/cjs/candid/idl.js +2228 -0
  128. package/lib/cjs/candid/idl.js.map +1 -0
  129. package/lib/cjs/candid/index.d.ts +30 -1
  130. package/lib/cjs/candid/index.d.ts.map +1 -1
  131. package/lib/cjs/candid/index.js +52 -1
  132. package/lib/cjs/candid/index.js.map +1 -1
  133. package/lib/cjs/candid/types.d.ts +6 -0
  134. package/lib/cjs/candid/types.d.ts.map +1 -0
  135. package/lib/cjs/candid/types.js +4 -0
  136. package/lib/cjs/candid/types.js.map +1 -0
  137. package/lib/cjs/candid/utils/bigint-math.d.ts +14 -0
  138. package/lib/cjs/candid/utils/bigint-math.d.ts.map +1 -0
  139. package/lib/cjs/candid/utils/bigint-math.js +30 -0
  140. package/lib/cjs/candid/utils/bigint-math.js.map +1 -0
  141. package/lib/cjs/candid/utils/buffer.d.ts +86 -0
  142. package/lib/cjs/candid/utils/buffer.d.ts.map +1 -0
  143. package/lib/cjs/candid/utils/buffer.js +191 -0
  144. package/lib/cjs/candid/utils/buffer.js.map +1 -0
  145. package/lib/cjs/candid/utils/hash.d.ts +7 -0
  146. package/lib/cjs/candid/utils/hash.d.ts.map +1 -0
  147. package/lib/cjs/candid/utils/hash.js +33 -0
  148. package/lib/cjs/candid/utils/hash.js.map +1 -0
  149. package/lib/cjs/candid/utils/leb128.d.ts +65 -0
  150. package/lib/cjs/candid/utils/leb128.d.ts.map +1 -0
  151. package/lib/cjs/candid/utils/leb128.js +228 -0
  152. package/lib/cjs/candid/utils/leb128.js.map +1 -0
  153. package/lib/cjs/identity/identity/delegation.d.ts +164 -0
  154. package/lib/cjs/identity/identity/delegation.d.ts.map +1 -0
  155. package/lib/cjs/identity/identity/delegation.js +302 -0
  156. package/lib/cjs/identity/identity/delegation.js.map +1 -0
  157. package/lib/cjs/identity/identity/ecdsa.d.ts +62 -0
  158. package/lib/cjs/identity/identity/ecdsa.d.ts.map +1 -0
  159. package/lib/cjs/identity/identity/ecdsa.js +117 -0
  160. package/lib/cjs/identity/identity/ecdsa.js.map +1 -0
  161. package/lib/cjs/identity/identity/ed25519.d.ts +67 -0
  162. package/lib/cjs/identity/identity/ed25519.d.ts.map +1 -0
  163. package/lib/cjs/identity/identity/ed25519.js +200 -0
  164. package/lib/cjs/identity/identity/ed25519.js.map +1 -0
  165. package/lib/cjs/identity/identity/partial.d.ts +34 -0
  166. package/lib/cjs/identity/identity/partial.d.ts.map +1 -0
  167. package/lib/cjs/identity/identity/partial.js +54 -0
  168. package/lib/cjs/identity/identity/partial.js.map +1 -0
  169. package/lib/cjs/identity/identity/webauthn.d.ts +51 -0
  170. package/lib/cjs/identity/identity/webauthn.d.ts.map +1 -0
  171. package/lib/cjs/identity/identity/webauthn.js +197 -0
  172. package/lib/cjs/identity/identity/webauthn.js.map +1 -0
  173. package/lib/cjs/identity/index.d.ts +38 -1
  174. package/lib/cjs/identity/index.d.ts.map +1 -1
  175. package/lib/cjs/identity/index.js +44 -1
  176. package/lib/cjs/identity/index.js.map +1 -1
  177. package/lib/cjs/identity/secp256k1/der.d.ts +33 -0
  178. package/lib/cjs/identity/secp256k1/der.d.ts.map +1 -0
  179. package/lib/cjs/identity/secp256k1/der.js +165 -0
  180. package/lib/cjs/identity/secp256k1/der.js.map +1 -0
  181. package/lib/cjs/identity/secp256k1/index.d.ts +51 -1
  182. package/lib/cjs/identity/secp256k1/index.d.ts.map +1 -1
  183. package/lib/cjs/identity/secp256k1/index.js +51 -1
  184. package/lib/cjs/identity/secp256k1/index.js.map +1 -1
  185. package/lib/cjs/identity/secp256k1/pem.d.ts +7 -0
  186. package/lib/cjs/identity/secp256k1/pem.d.ts.map +1 -0
  187. package/lib/cjs/identity/secp256k1/pem.js +75 -0
  188. package/lib/cjs/identity/secp256k1/pem.js.map +1 -0
  189. package/lib/cjs/identity/secp256k1/secp256k1.d.ts +87 -0
  190. package/lib/cjs/identity/secp256k1/secp256k1.d.ts.map +1 -0
  191. package/lib/cjs/identity/secp256k1/secp256k1.js +260 -0
  192. package/lib/cjs/identity/secp256k1/secp256k1.js.map +1 -0
  193. package/lib/cjs/principal/index.d.ts +18 -1
  194. package/lib/cjs/principal/index.d.ts.map +1 -1
  195. package/lib/cjs/principal/index.js +22 -1
  196. package/lib/cjs/principal/index.js.map +1 -1
  197. package/lib/cjs/principal/principal.d.ts +50 -0
  198. package/lib/cjs/principal/principal.d.ts.map +1 -0
  199. package/lib/cjs/principal/principal.js +148 -0
  200. package/lib/cjs/principal/principal.js.map +1 -0
  201. package/lib/cjs/principal/utils/base32.d.ts +10 -0
  202. package/lib/cjs/principal/utils/base32.d.ts.map +1 -0
  203. package/lib/cjs/principal/utils/base32.js +90 -0
  204. package/lib/cjs/principal/utils/base32.js.map +1 -0
  205. package/lib/cjs/principal/utils/getCrc.d.ts +6 -0
  206. package/lib/cjs/principal/utils/getCrc.d.ts.map +1 -0
  207. package/lib/cjs/principal/utils/getCrc.js +53 -0
  208. package/lib/cjs/principal/utils/getCrc.js.map +1 -0
  209. package/lib/esm/agent/actor.d.ts +203 -0
  210. package/lib/esm/agent/actor.d.ts.map +1 -0
  211. package/lib/esm/agent/actor.js +337 -0
  212. package/lib/esm/agent/actor.js.map +1 -0
  213. package/lib/esm/agent/agent/api.d.ts +216 -0
  214. package/lib/esm/agent/agent/api.d.ts.map +1 -0
  215. package/lib/esm/agent/agent/api.js +34 -0
  216. package/lib/esm/agent/agent/api.js.map +1 -0
  217. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts +37 -0
  218. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -0
  219. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js +48 -0
  220. package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -0
  221. package/lib/esm/agent/agent/http/index.d.ts +190 -0
  222. package/lib/esm/agent/agent/http/index.d.ts.map +1 -0
  223. package/lib/esm/agent/agent/http/index.js +1117 -0
  224. package/lib/esm/agent/agent/http/index.js.map +1 -0
  225. package/lib/esm/agent/agent/http/transforms.d.ts +54 -0
  226. package/lib/esm/agent/agent/http/transforms.d.ts.map +1 -0
  227. package/lib/esm/agent/agent/http/transforms.js +128 -0
  228. package/lib/esm/agent/agent/http/transforms.js.map +1 -0
  229. package/lib/esm/agent/agent/http/types.d.ts +81 -0
  230. package/lib/esm/agent/agent/http/types.d.ts.map +1 -0
  231. package/lib/esm/agent/agent/http/types.js +39 -0
  232. package/lib/esm/agent/agent/http/types.js.map +1 -0
  233. package/lib/esm/agent/agent/index.d.ts +3 -0
  234. package/lib/esm/agent/agent/index.d.ts.map +1 -0
  235. package/lib/esm/agent/agent/index.js +3 -0
  236. package/lib/esm/agent/agent/index.js.map +1 -0
  237. package/lib/esm/agent/auth.d.ts +91 -0
  238. package/lib/esm/agent/auth.d.ts.map +1 -0
  239. package/lib/esm/agent/auth.js +59 -0
  240. package/lib/esm/agent/auth.js.map +1 -0
  241. package/lib/esm/agent/canister-env/index.d.ts +111 -1
  242. package/lib/esm/agent/canister-env/index.d.ts.map +1 -1
  243. package/lib/esm/agent/canister-env/index.js +111 -1
  244. package/lib/esm/agent/canister-env/index.js.map +1 -1
  245. package/lib/esm/agent/canisterStatus/index.d.ts +61 -0
  246. package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -0
  247. package/lib/esm/agent/canisterStatus/index.js +199 -0
  248. package/lib/esm/agent/canisterStatus/index.js.map +1 -0
  249. package/lib/esm/agent/cbor.d.ts +26 -0
  250. package/lib/esm/agent/cbor.d.ts.map +1 -0
  251. package/lib/esm/agent/cbor.js +54 -0
  252. package/lib/esm/agent/cbor.js.map +1 -0
  253. package/lib/esm/agent/certificate.d.ts +286 -0
  254. package/lib/esm/agent/certificate.d.ts.map +1 -0
  255. package/lib/esm/agent/certificate.js +712 -0
  256. package/lib/esm/agent/certificate.js.map +1 -0
  257. package/lib/esm/agent/constants.d.ts +18 -0
  258. package/lib/esm/agent/constants.d.ts.map +1 -0
  259. package/lib/esm/agent/constants.js +19 -0
  260. package/lib/esm/agent/constants.js.map +1 -0
  261. package/lib/esm/agent/der.d.ts +34 -0
  262. package/lib/esm/agent/der.d.ts.map +1 -0
  263. package/lib/esm/agent/der.js +166 -0
  264. package/lib/esm/agent/der.js.map +1 -0
  265. package/lib/esm/agent/errors.d.ts +386 -0
  266. package/lib/esm/agent/errors.d.ts.map +1 -0
  267. package/lib/esm/agent/errors.js +689 -0
  268. package/lib/esm/agent/errors.js.map +1 -0
  269. package/lib/esm/agent/fetch_candid.d.ts +9 -0
  270. package/lib/esm/agent/fetch_candid.d.ts.map +1 -0
  271. package/lib/esm/agent/fetch_candid.js +33 -0
  272. package/lib/esm/agent/fetch_candid.js.map +1 -0
  273. package/lib/esm/agent/index.d.ts +125 -1
  274. package/lib/esm/agent/index.d.ts.map +1 -1
  275. package/lib/esm/agent/index.js +125 -1
  276. package/lib/esm/agent/index.js.map +1 -1
  277. package/lib/esm/agent/observable.d.ts +24 -0
  278. package/lib/esm/agent/observable.d.ts.map +1 -0
  279. package/lib/esm/agent/observable.js +29 -0
  280. package/lib/esm/agent/observable.js.map +1 -0
  281. package/lib/esm/agent/polling/backoff.d.ts +50 -0
  282. package/lib/esm/agent/polling/backoff.d.ts.map +1 -0
  283. package/lib/esm/agent/polling/backoff.js +85 -0
  284. package/lib/esm/agent/polling/backoff.js.map +1 -0
  285. package/lib/esm/agent/polling/index.d.ts +63 -0
  286. package/lib/esm/agent/polling/index.d.ts.map +1 -0
  287. package/lib/esm/agent/polling/index.js +144 -0
  288. package/lib/esm/agent/polling/index.js.map +1 -0
  289. package/lib/esm/agent/polling/strategy.d.ts +52 -0
  290. package/lib/esm/agent/polling/strategy.d.ts.map +1 -0
  291. package/lib/esm/agent/polling/strategy.js +94 -0
  292. package/lib/esm/agent/polling/strategy.js.map +1 -0
  293. package/lib/esm/agent/public_key.d.ts +16 -0
  294. package/lib/esm/agent/public_key.d.ts.map +1 -0
  295. package/lib/esm/agent/public_key.js +48 -0
  296. package/lib/esm/agent/public_key.js.map +1 -0
  297. package/lib/esm/agent/request_id.d.ts +24 -0
  298. package/lib/esm/agent/request_id.d.ts.map +1 -0
  299. package/lib/esm/agent/request_id.js +83 -0
  300. package/lib/esm/agent/request_id.js.map +1 -0
  301. package/lib/esm/agent/subnetStatus/index.d.ts +70 -0
  302. package/lib/esm/agent/subnetStatus/index.d.ts.map +1 -0
  303. package/lib/esm/agent/subnetStatus/index.js +183 -0
  304. package/lib/esm/agent/subnetStatus/index.js.map +1 -0
  305. package/lib/esm/agent/utils/bls.d.ts +10 -0
  306. package/lib/esm/agent/utils/bls.d.ts.map +1 -0
  307. package/lib/esm/agent/utils/bls.js +17 -0
  308. package/lib/esm/agent/utils/bls.js.map +1 -0
  309. package/lib/esm/agent/utils/buffer.d.ts +22 -0
  310. package/lib/esm/agent/utils/buffer.d.ts.map +1 -0
  311. package/lib/esm/agent/utils/buffer.js +50 -0
  312. package/lib/esm/agent/utils/buffer.js.map +1 -0
  313. package/lib/esm/agent/utils/expirableMap.d.ts +80 -0
  314. package/lib/esm/agent/utils/expirableMap.d.ts.map +1 -0
  315. package/lib/esm/agent/utils/expirableMap.js +144 -0
  316. package/lib/esm/agent/utils/expirableMap.js.map +1 -0
  317. package/lib/esm/agent/utils/leb.d.ts +3 -0
  318. package/lib/esm/agent/utils/leb.d.ts.map +1 -0
  319. package/lib/esm/agent/utils/leb.js +12 -0
  320. package/lib/esm/agent/utils/leb.js.map +1 -0
  321. package/lib/esm/agent/utils/random.d.ts +6 -0
  322. package/lib/esm/agent/utils/random.d.ts.map +1 -0
  323. package/lib/esm/agent/utils/random.js +25 -0
  324. package/lib/esm/agent/utils/random.js.map +1 -0
  325. package/lib/esm/agent/utils/readState.d.ts +84 -0
  326. package/lib/esm/agent/utils/readState.d.ts.map +1 -0
  327. package/lib/esm/agent/utils/readState.js +107 -0
  328. package/lib/esm/agent/utils/readState.js.map +1 -0
  329. package/lib/esm/candid/candid-core.d.ts +72 -0
  330. package/lib/esm/candid/candid-core.d.ts.map +1 -0
  331. package/lib/esm/candid/candid-core.js +241 -0
  332. package/lib/esm/candid/candid-core.js.map +1 -0
  333. package/lib/esm/candid/candid-ui.d.ts +35 -0
  334. package/lib/esm/candid/candid-ui.d.ts.map +1 -0
  335. package/lib/esm/candid/candid-ui.js +272 -0
  336. package/lib/esm/candid/candid-ui.js.map +1 -0
  337. package/lib/esm/candid/idl.d.ts +579 -0
  338. package/lib/esm/candid/idl.d.ts.map +1 -0
  339. package/lib/esm/candid/idl.js +2189 -0
  340. package/lib/esm/candid/idl.js.map +1 -0
  341. package/lib/esm/candid/index.d.ts +30 -1
  342. package/lib/esm/candid/index.d.ts.map +1 -1
  343. package/lib/esm/candid/index.js +29 -1
  344. package/lib/esm/candid/index.js.map +1 -1
  345. package/lib/esm/candid/types.d.ts +6 -0
  346. package/lib/esm/candid/types.d.ts.map +1 -0
  347. package/lib/esm/candid/types.js +3 -0
  348. package/lib/esm/candid/types.js.map +1 -0
  349. package/lib/esm/candid/utils/bigint-math.d.ts +14 -0
  350. package/lib/esm/candid/utils/bigint-math.d.ts.map +1 -0
  351. package/lib/esm/candid/utils/bigint-math.js +26 -0
  352. package/lib/esm/candid/utils/bigint-math.js.map +1 -0
  353. package/lib/esm/candid/utils/buffer.d.ts +86 -0
  354. package/lib/esm/candid/utils/buffer.d.ts.map +1 -0
  355. package/lib/esm/candid/utils/buffer.js +182 -0
  356. package/lib/esm/candid/utils/buffer.js.map +1 -0
  357. package/lib/esm/candid/utils/hash.d.ts +7 -0
  358. package/lib/esm/candid/utils/hash.d.ts.map +1 -0
  359. package/lib/esm/candid/utils/hash.js +30 -0
  360. package/lib/esm/candid/utils/hash.js.map +1 -0
  361. package/lib/esm/candid/utils/leb128.d.ts +65 -0
  362. package/lib/esm/candid/utils/leb128.d.ts.map +1 -0
  363. package/lib/esm/candid/utils/leb128.js +216 -0
  364. package/lib/esm/candid/utils/leb128.js.map +1 -0
  365. package/lib/esm/identity/identity/delegation.d.ts +164 -0
  366. package/lib/esm/identity/identity/delegation.d.ts.map +1 -0
  367. package/lib/esm/identity/identity/delegation.js +294 -0
  368. package/lib/esm/identity/identity/delegation.js.map +1 -0
  369. package/lib/esm/identity/identity/ecdsa.d.ts +62 -0
  370. package/lib/esm/identity/identity/ecdsa.d.ts.map +1 -0
  371. package/lib/esm/identity/identity/ecdsa.js +112 -0
  372. package/lib/esm/identity/identity/ecdsa.js.map +1 -0
  373. package/lib/esm/identity/identity/ed25519.d.ts +67 -0
  374. package/lib/esm/identity/identity/ed25519.d.ts.map +1 -0
  375. package/lib/esm/identity/identity/ed25519.js +195 -0
  376. package/lib/esm/identity/identity/ed25519.js.map +1 -0
  377. package/lib/esm/identity/identity/partial.d.ts +34 -0
  378. package/lib/esm/identity/identity/partial.d.ts.map +1 -0
  379. package/lib/esm/identity/identity/partial.js +50 -0
  380. package/lib/esm/identity/identity/partial.js.map +1 -0
  381. package/lib/esm/identity/identity/webauthn.d.ts +51 -0
  382. package/lib/esm/identity/identity/webauthn.d.ts.map +1 -0
  383. package/lib/esm/identity/identity/webauthn.js +192 -0
  384. package/lib/esm/identity/identity/webauthn.js.map +1 -0
  385. package/lib/esm/identity/index.d.ts +38 -1
  386. package/lib/esm/identity/index.d.ts.map +1 -1
  387. package/lib/esm/identity/index.js +38 -1
  388. package/lib/esm/identity/index.js.map +1 -1
  389. package/lib/esm/identity/secp256k1/der.d.ts +33 -0
  390. package/lib/esm/identity/secp256k1/der.d.ts.map +1 -0
  391. package/lib/esm/identity/secp256k1/der.js +156 -0
  392. package/lib/esm/identity/secp256k1/der.js.map +1 -0
  393. package/lib/esm/identity/secp256k1/index.d.ts +51 -1
  394. package/lib/esm/identity/secp256k1/index.d.ts.map +1 -1
  395. package/lib/esm/identity/secp256k1/index.js +51 -1
  396. package/lib/esm/identity/secp256k1/index.js.map +1 -1
  397. package/lib/esm/identity/secp256k1/pem.d.ts +7 -0
  398. package/lib/esm/identity/secp256k1/pem.d.ts.map +1 -0
  399. package/lib/esm/identity/secp256k1/pem.js +39 -0
  400. package/lib/esm/identity/secp256k1/pem.js.map +1 -0
  401. package/lib/esm/identity/secp256k1/secp256k1.d.ts +87 -0
  402. package/lib/esm/identity/secp256k1/secp256k1.d.ts.map +1 -0
  403. package/lib/esm/identity/secp256k1/secp256k1.js +222 -0
  404. package/lib/esm/identity/secp256k1/secp256k1.js.map +1 -0
  405. package/lib/esm/principal/index.d.ts +18 -1
  406. package/lib/esm/principal/index.d.ts.map +1 -1
  407. package/lib/esm/principal/index.js +18 -1
  408. package/lib/esm/principal/index.js.map +1 -1
  409. package/lib/esm/principal/principal.d.ts +50 -0
  410. package/lib/esm/principal/principal.d.ts.map +1 -0
  411. package/lib/esm/principal/principal.js +144 -0
  412. package/lib/esm/principal/principal.js.map +1 -0
  413. package/lib/esm/principal/utils/base32.d.ts +10 -0
  414. package/lib/esm/principal/utils/base32.d.ts.map +1 -0
  415. package/lib/esm/principal/utils/base32.js +86 -0
  416. package/lib/esm/principal/utils/base32.js.map +1 -0
  417. package/lib/esm/principal/utils/getCrc.d.ts +6 -0
  418. package/lib/esm/principal/utils/getCrc.d.ts.map +1 -0
  419. package/lib/esm/principal/utils/getCrc.js +50 -0
  420. package/lib/esm/principal/utils/getCrc.js.map +1 -0
  421. package/package.json +17 -11
  422. package/src/agent/actor.ts +576 -0
  423. package/src/agent/agent/api.ts +262 -0
  424. package/src/agent/agent/http/index.ts +1518 -0
  425. package/src/agent/agent/http/transforms.ts +158 -0
  426. package/src/agent/agent/http/types.ts +126 -0
  427. package/src/agent/agent/index.ts +2 -0
  428. package/src/agent/auth.ts +147 -0
  429. package/src/agent/canister-env/index.ts +192 -1
  430. package/src/agent/canisterStatus/index.ts +267 -0
  431. package/src/agent/cbor.ts +63 -0
  432. package/src/agent/certificate.ts +1060 -0
  433. package/src/agent/constants.ts +24 -0
  434. package/src/agent/der.ts +170 -0
  435. package/src/agent/errors.ts +881 -0
  436. package/src/agent/fetch_candid.ts +37 -0
  437. package/src/agent/index.ts +131 -1
  438. package/src/agent/observable.ts +49 -0
  439. package/src/agent/polling/backoff.ts +130 -0
  440. package/src/agent/polling/index.ts +250 -0
  441. package/src/agent/polling/strategy.ts +144 -0
  442. package/src/agent/public_key.ts +65 -0
  443. package/src/agent/request_id.ts +92 -0
  444. package/src/agent/subnetStatus/index.ts +270 -0
  445. package/src/agent/utils/bls.ts +18 -0
  446. package/src/agent/utils/buffer.ts +60 -0
  447. package/src/agent/utils/expirableMap.ts +163 -0
  448. package/src/agent/utils/leb.ts +14 -0
  449. package/src/agent/utils/random.ts +30 -0
  450. package/src/agent/utils/readState.ts +180 -0
  451. package/src/candid/candid-core.ts +276 -0
  452. package/src/candid/candid-ui.ts +289 -0
  453. package/src/candid/idl.ts +2556 -0
  454. package/src/candid/index.ts +35 -1
  455. package/src/candid/types.ts +7 -0
  456. package/src/candid/utils/bigint-math.ts +26 -0
  457. package/src/candid/utils/buffer.ts +221 -0
  458. package/src/candid/utils/hash.ts +31 -0
  459. package/src/candid/utils/leb128.ts +234 -0
  460. package/src/identity/identity/delegation.ts +411 -0
  461. package/src/identity/identity/ecdsa.ts +158 -0
  462. package/src/identity/identity/ed25519.ts +239 -0
  463. package/src/identity/identity/partial.ts +60 -0
  464. package/src/identity/identity/webauthn.ts +265 -0
  465. package/src/identity/index.ts +39 -1
  466. package/src/identity/secp256k1/der.ts +156 -0
  467. package/src/identity/secp256k1/index.ts +52 -1
  468. package/src/identity/secp256k1/pem.ts +40 -0
  469. package/src/identity/secp256k1/secp256k1.ts +270 -0
  470. package/src/package.json +4 -0
  471. package/src/principal/index.ts +19 -1
  472. package/src/principal/principal.ts +171 -0
  473. package/src/principal/utils/base32.ts +101 -0
  474. package/src/principal/utils/getCrc.ts +52 -0
@@ -0,0 +1,1060 @@
1
+ import * as cbor from './cbor.ts';
2
+ import {
3
+ CertificateHasTooManyDelegationsErrorCode,
4
+ CertificateNotAuthorizedErrorCode,
5
+ CertificateTimeErrorCode,
6
+ CertificateVerificationErrorCode,
7
+ DerKeyLengthMismatchErrorCode,
8
+ DerPrefixMismatchErrorCode,
9
+ ProtocolError,
10
+ LookupErrorCode,
11
+ TrustError,
12
+ UnknownError,
13
+ HashTreeDecodeErrorCode,
14
+ UNREACHABLE_ERROR,
15
+ MissingLookupValueErrorCode,
16
+ UnexpectedErrorCode,
17
+ CertificateNotAuthorizedForSubnetErrorCode,
18
+ } from './errors.ts';
19
+ import { Principal } from '#principal';
20
+ import { compare as uint8Compare } from '#candid';
21
+ import * as bls from './utils/bls.ts';
22
+ import { decodeTime } from './utils/leb.ts';
23
+ import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
24
+ import { uint8Equals } from './utils/buffer.ts';
25
+ import { sha256 } from '@noble/hashes/sha2';
26
+ import type { HttpAgent } from './agent/http/index.ts';
27
+ import type { Agent } from './agent/api.ts';
28
+ import { IC_STATE_ROOT_DOMAIN_SEPARATOR } from './constants.ts';
29
+
30
+ const MINUTES_TO_MSEC = 60 * 1000;
31
+ const HOURS_TO_MINUTES = 60;
32
+ const DAYS_TO_HOURS = 24;
33
+ const DAYS_TO_MINUTES = DAYS_TO_HOURS * HOURS_TO_MINUTES;
34
+
35
+ const DEFAULT_CERTIFICATE_MAX_AGE_IN_MINUTES = 5;
36
+ const DEFAULT_CERTIFICATE_MAX_MINUTES_IN_FUTURE = 5;
37
+ // For now, we don't want to set a strict timeout on the certificate delegation freshness,
38
+ // so we set the max age really far in the past.
39
+ const DEFAULT_CERTIFICATE_DELEGATION_MAX_AGE_IN_MINUTES = 30 * DAYS_TO_MINUTES;
40
+
41
+ export interface Cert {
42
+ tree: HashTree;
43
+ signature: Uint8Array;
44
+ delegation?: Delegation;
45
+ }
46
+
47
+ export enum NodeType {
48
+ Empty = 0,
49
+ Fork = 1,
50
+ Labeled = 2,
51
+ Leaf = 3,
52
+ Pruned = 4,
53
+ }
54
+
55
+ export type NodePath = Array<Uint8Array | string>;
56
+ export type NodeLabel = Uint8Array & { __nodeLabel__: void };
57
+ export type NodeValue = Uint8Array & { __nodeValue__: void };
58
+ export type NodeHash = Uint8Array & { __nodeHash__: void };
59
+
60
+ export type EmptyHashTree = [NodeType.Empty];
61
+ export type ForkHashTree = [NodeType.Fork, HashTree, HashTree];
62
+ export type LabeledHashTree = [NodeType.Labeled, NodeLabel, HashTree];
63
+ export type LeafHashTree = [NodeType.Leaf, NodeValue];
64
+ export type PrunedHashTree = [NodeType.Pruned, NodeHash];
65
+
66
+ export type HashTree =
67
+ | EmptyHashTree
68
+ | ForkHashTree
69
+ | LabeledHashTree
70
+ | LeafHashTree
71
+ | PrunedHashTree;
72
+
73
+ /**
74
+ * Make a human readable string out of a hash tree.
75
+ * @param tree The hash tree to convert to a string
76
+ */
77
+ export function hashTreeToString(tree: HashTree): string {
78
+ const indent = (s: string) =>
79
+ s
80
+ .split('\n')
81
+ .map(x => ' ' + x)
82
+ .join('\n');
83
+ function labelToString(label: Uint8Array): string {
84
+ const decoder = new TextDecoder(undefined, { fatal: true });
85
+ try {
86
+ return JSON.stringify(decoder.decode(label));
87
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
88
+ } catch (e) {
89
+ return `data(...${label.byteLength} bytes)`;
90
+ }
91
+ }
92
+
93
+ switch (tree[0]) {
94
+ case NodeType.Empty:
95
+ return '()';
96
+ case NodeType.Fork: {
97
+ if (tree[1] instanceof Array && tree[2] instanceof Uint8Array) {
98
+ const left = hashTreeToString(tree[1]);
99
+ const right = hashTreeToString(tree[2]);
100
+ return `sub(\n left:\n${indent(left)}\n---\n right:\n${indent(right)}\n)`;
101
+ } else {
102
+ throw UnknownError.fromCode(new HashTreeDecodeErrorCode('Invalid tree structure for fork'));
103
+ }
104
+ }
105
+ case NodeType.Labeled: {
106
+ if (tree[1] instanceof Uint8Array && tree[2] instanceof Uint8Array) {
107
+ const label = labelToString(tree[1]);
108
+ const sub = hashTreeToString(tree[2]);
109
+ return `label(\n label:\n${indent(label)}\n sub:\n${indent(sub)}\n)`;
110
+ } else {
111
+ throw UnknownError.fromCode(
112
+ new HashTreeDecodeErrorCode('Invalid tree structure for labeled'),
113
+ );
114
+ }
115
+ }
116
+ case NodeType.Leaf: {
117
+ if (!tree[1]) {
118
+ throw UnknownError.fromCode(new HashTreeDecodeErrorCode('Invalid tree structure for leaf'));
119
+ } else if (Array.isArray(tree[1])) {
120
+ return JSON.stringify(tree[1]);
121
+ }
122
+ return `leaf(...${tree[1].byteLength} bytes)`;
123
+ }
124
+ case NodeType.Pruned: {
125
+ if (!tree[1]) {
126
+ throw UnknownError.fromCode(
127
+ new HashTreeDecodeErrorCode('Invalid tree structure for pruned'),
128
+ );
129
+ } else if (Array.isArray(tree[1])) {
130
+ return JSON.stringify(tree[1]);
131
+ }
132
+
133
+ return `pruned(${bytesToHex(new Uint8Array(tree[1]))}`;
134
+ }
135
+ default: {
136
+ return `unknown(${JSON.stringify(tree[0])})`;
137
+ }
138
+ }
139
+ }
140
+
141
+ interface Delegation extends Record<string, unknown> {
142
+ subnet_id: Uint8Array;
143
+ certificate: Uint8Array;
144
+ }
145
+
146
+ function isBufferGreaterThan(a: Uint8Array, b: Uint8Array): boolean {
147
+ for (let i = 0; i < a.length; i++) {
148
+ if (a[i] > b[i]) {
149
+ return true;
150
+ }
151
+ }
152
+ return false;
153
+ }
154
+
155
+ type VerifyFunc = (pk: Uint8Array, sig: Uint8Array, msg: Uint8Array) => Promise<boolean> | boolean;
156
+
157
+ export type CertificatePrincipal =
158
+ | {
159
+ /**
160
+ * The effective canister ID of the request when verifying a response, or
161
+ * the signing canister ID when verifying a certified variable.
162
+ */
163
+ canisterId: Principal;
164
+ }
165
+ | {
166
+ /**
167
+ * The subnet ID when verifying a certificate from a subnet.
168
+ */
169
+ subnetId: Principal;
170
+ };
171
+
172
+ export interface CreateCertificateOptions {
173
+ /**
174
+ * The bytes encoding the certificate to be verified
175
+ */
176
+ certificate: Uint8Array;
177
+ /**
178
+ * The root key against which to verify the certificate
179
+ * (normally, the root key of the IC main network)
180
+ */
181
+ rootKey: Uint8Array;
182
+ /**
183
+ * The principal for which the certificate is being verified.
184
+ */
185
+ principal: CertificatePrincipal;
186
+ /**
187
+ * BLS Verification strategy. Default strategy uses bls12_381 from @noble/curves
188
+ */
189
+ blsVerify?: VerifyFunc;
190
+
191
+ /**
192
+ * The maximum age of the certificate in minutes. Default is 5 minutes.
193
+ * This is used to verify the time the certificate was signed, particularly for validating Delegation certificates, which can live for longer than the default window of +/- 5 minutes. If the certificate is
194
+ * older than the specified age, it will fail verification.
195
+ * @default 5
196
+ */
197
+ maxAgeInMinutes?: number;
198
+
199
+ /**
200
+ * Overrides the maxAgeInMinutes setting and skips comparing the client's time against the certificate. Used for scenarios where the machine's clock is known to be out of sync, or for inspecting expired certificates.
201
+ * @default false
202
+ */
203
+ disableTimeVerification?: boolean;
204
+
205
+ /**
206
+ * The agent used to sync time with the IC network, if the certificate fails the freshness check.
207
+ * If the agent does not implement the {@link HttpAgent.getTimeDiffMsecs}, {@link HttpAgent.hasSyncedTime}, {@link HttpAgent.syncTime} and {@link HttpAgent.syncTimeWithSubnet} methods,
208
+ * time will not be synced in case of a freshness check failure.
209
+ * @default undefined
210
+ */
211
+ agent?: Agent;
212
+ }
213
+
214
+ export class Certificate {
215
+ public cert: Cert;
216
+ #disableTimeVerification: boolean = false;
217
+ #agent:
218
+ | Pick<HttpAgent, 'getTimeDiffMsecs' | 'hasSyncedTime' | 'syncTime' | 'syncTimeWithSubnet'>
219
+ | undefined = undefined;
220
+
221
+ /**
222
+ * Create a new instance of a certificate, automatically verifying it.
223
+ * @param {CreateCertificateOptions} options {@link CreateCertificateOptions}
224
+ * @throws if the verification of the certificate fails
225
+ */
226
+ public static async create(options: CreateCertificateOptions): Promise<Certificate> {
227
+ const cert = Certificate.createUnverified(options);
228
+
229
+ await cert.verify();
230
+ return cert;
231
+ }
232
+
233
+ private static createUnverified(options: CreateCertificateOptions): Certificate {
234
+ return new Certificate(
235
+ options.certificate,
236
+ options.rootKey,
237
+ options.principal,
238
+ options.blsVerify ?? bls.blsVerify,
239
+ options.maxAgeInMinutes,
240
+ options.disableTimeVerification,
241
+ options.agent,
242
+ );
243
+ }
244
+
245
+ private constructor(
246
+ certificate: Uint8Array,
247
+ private _rootKey: Uint8Array,
248
+ private _principal: CertificatePrincipal,
249
+ private _blsVerify: VerifyFunc,
250
+ private _maxAgeInMinutes: number = DEFAULT_CERTIFICATE_MAX_AGE_IN_MINUTES,
251
+ disableTimeVerification: boolean = false,
252
+ agent?: Agent,
253
+ ) {
254
+ this.#disableTimeVerification = disableTimeVerification;
255
+ this.cert = cbor.decode(certificate);
256
+
257
+ if (
258
+ agent &&
259
+ 'getTimeDiffMsecs' in agent &&
260
+ 'hasSyncedTime' in agent &&
261
+ 'syncTime' in agent &&
262
+ 'syncTimeWithSubnet' in agent
263
+ ) {
264
+ this.#agent = agent as Pick<
265
+ HttpAgent,
266
+ 'getTimeDiffMsecs' | 'hasSyncedTime' | 'syncTime' | 'syncTimeWithSubnet'
267
+ >;
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Lookup a path in the certificate tree, using {@link lookup_path}.
273
+ * @param path The path to lookup.
274
+ * @returns The result of the lookup.
275
+ */
276
+ public lookup_path(path: NodePath): LookupResult {
277
+ return lookup_path(path, this.cert.tree);
278
+ }
279
+
280
+ /**
281
+ * Lookup a subtree in the certificate tree, using {@link lookup_subtree}.
282
+ * @param path The path to lookup.
283
+ * @returns The result of the lookup.
284
+ */
285
+ public lookup_subtree(path: NodePath): SubtreeLookupResult {
286
+ return lookup_subtree(path, this.cert.tree);
287
+ }
288
+
289
+ private async verify(): Promise<void> {
290
+ const rootHash = await reconstruct(this.cert.tree);
291
+ const derKey = await this._checkDelegationAndGetKey(this.cert.delegation);
292
+ const sig = this.cert.signature;
293
+ const key = extractDER(derKey);
294
+ const msg = concatBytes(IC_STATE_ROOT_DOMAIN_SEPARATOR, rootHash);
295
+
296
+ const lookupTime = lookupResultToBuffer(this.lookup_path(['time']));
297
+ if (!lookupTime) {
298
+ // Should never happen - time is always present in IC certificates
299
+ throw ProtocolError.fromCode(
300
+ new CertificateVerificationErrorCode('Certificate does not contain a time'),
301
+ );
302
+ }
303
+
304
+ // Certificate time verification checks
305
+ if (!this.#disableTimeVerification) {
306
+ const timeDiffMsecs = this.#agent?.getTimeDiffMsecs() ?? 0;
307
+ const maxAgeInMsec = this._maxAgeInMinutes * MINUTES_TO_MSEC;
308
+ const now = new Date();
309
+ const adjustedNow = now.getTime() + timeDiffMsecs;
310
+ const earliestCertificateTime = adjustedNow - maxAgeInMsec;
311
+ const latestCertificateTime =
312
+ adjustedNow + DEFAULT_CERTIFICATE_MAX_MINUTES_IN_FUTURE * MINUTES_TO_MSEC;
313
+
314
+ const certTime = decodeTime(lookupTime);
315
+
316
+ const isCertificateTimePast = certTime.getTime() < earliestCertificateTime;
317
+ const isCertificateTimeFuture = certTime.getTime() > latestCertificateTime;
318
+
319
+ if (
320
+ (isCertificateTimePast || isCertificateTimeFuture) &&
321
+ this.#agent &&
322
+ !this.#agent.hasSyncedTime()
323
+ ) {
324
+ await this._syncTime();
325
+ return await this.verify();
326
+ }
327
+
328
+ if (isCertificateTimePast) {
329
+ throw TrustError.fromCode(
330
+ new CertificateTimeErrorCode(this._maxAgeInMinutes, certTime, now, timeDiffMsecs, 'past'),
331
+ );
332
+ } else if (isCertificateTimeFuture) {
333
+ if (this.#agent?.hasSyncedTime()) {
334
+ // This case should never happen, and it signals a bug in either the replica or the local system.
335
+ throw UnknownError.fromCode(
336
+ new UnexpectedErrorCode(
337
+ 'System time has been synced with the IC network, but certificate is still too far in the future.',
338
+ ),
339
+ );
340
+ }
341
+ throw TrustError.fromCode(
342
+ new CertificateTimeErrorCode(5, certTime, now, timeDiffMsecs, 'future'),
343
+ );
344
+ }
345
+ }
346
+
347
+ try {
348
+ const sigVer = await this._blsVerify(key, sig, msg);
349
+ if (!sigVer) {
350
+ throw TrustError.fromCode(new CertificateVerificationErrorCode('Invalid signature'));
351
+ }
352
+ } catch (err) {
353
+ throw TrustError.fromCode(
354
+ new CertificateVerificationErrorCode('Signature verification failed', err),
355
+ );
356
+ }
357
+ }
358
+
359
+ private async _checkDelegationAndGetKey(d: Delegation | undefined): Promise<Uint8Array> {
360
+ if (!d) {
361
+ return this._rootKey;
362
+ }
363
+
364
+ const cert = Certificate.createUnverified({
365
+ certificate: d.certificate,
366
+ rootKey: this._rootKey,
367
+ principal: this._principal,
368
+ blsVerify: this._blsVerify,
369
+ disableTimeVerification: this.#disableTimeVerification,
370
+ maxAgeInMinutes: DEFAULT_CERTIFICATE_DELEGATION_MAX_AGE_IN_MINUTES,
371
+ agent: this.#agent as HttpAgent,
372
+ });
373
+
374
+ if (cert.cert.delegation) {
375
+ throw ProtocolError.fromCode(new CertificateHasTooManyDelegationsErrorCode());
376
+ }
377
+
378
+ await cert.verify();
379
+
380
+ let subnetId: Principal;
381
+
382
+ if (isCanisterPrincipal(this._principal)) {
383
+ const canisterId = this._principal.canisterId;
384
+ subnetId = Principal.fromUint8Array(d.subnet_id);
385
+
386
+ const canisterInRange = check_canister_ranges({
387
+ canisterId,
388
+ subnetId,
389
+ tree: cert.cert.tree,
390
+ });
391
+ if (!canisterInRange) {
392
+ throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(canisterId, subnetId));
393
+ }
394
+ } else if (isSubnetPrincipal(this._principal)) {
395
+ subnetId = this._principal.subnetId;
396
+ } else {
397
+ throw UNREACHABLE_ERROR;
398
+ }
399
+
400
+ const publicKeyLookup = lookupResultToBuffer(
401
+ cert.lookup_path(['subnet', subnetId.toUint8Array(), 'public_key']),
402
+ );
403
+ if (!publicKeyLookup) {
404
+ if (isSubnetPrincipal(this._principal)) {
405
+ throw TrustError.fromCode(new CertificateNotAuthorizedForSubnetErrorCode(subnetId));
406
+ } else {
407
+ throw TrustError.fromCode(
408
+ new MissingLookupValueErrorCode(
409
+ `Could not find subnet key for subnet ID ${subnetId.toText()}`,
410
+ ),
411
+ );
412
+ }
413
+ }
414
+ return publicKeyLookup;
415
+ }
416
+
417
+ private async _syncTime(): Promise<void> {
418
+ if (!this.#agent) {
419
+ return;
420
+ }
421
+
422
+ if (isCanisterPrincipal(this._principal)) {
423
+ await this.#agent.syncTime(this._principal.canisterId);
424
+ } else {
425
+ await this.#agent.syncTimeWithSubnet(this._principal.subnetId);
426
+ }
427
+ }
428
+ }
429
+
430
+ function isSubnetPrincipal<T extends CertificatePrincipal>(
431
+ principal: T,
432
+ ): principal is T & { subnetId: Principal } {
433
+ return 'subnetId' in principal;
434
+ }
435
+
436
+ function isCanisterPrincipal<T extends CertificatePrincipal>(
437
+ principal: T,
438
+ ): principal is T & { canisterId: Principal } {
439
+ return 'canisterId' in principal;
440
+ }
441
+
442
+ const DER_PREFIX = hexToBytes(
443
+ '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100',
444
+ );
445
+ const KEY_LENGTH = 96;
446
+
447
+ function extractDER(buf: Uint8Array): Uint8Array {
448
+ const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;
449
+ if (buf.byteLength !== expectedLength) {
450
+ throw ProtocolError.fromCode(new DerKeyLengthMismatchErrorCode(expectedLength, buf.byteLength));
451
+ }
452
+ const prefix = buf.slice(0, DER_PREFIX.byteLength);
453
+ if (!uint8Equals(prefix, DER_PREFIX)) {
454
+ throw ProtocolError.fromCode(new DerPrefixMismatchErrorCode(DER_PREFIX, prefix));
455
+ }
456
+
457
+ return buf.slice(DER_PREFIX.byteLength);
458
+ }
459
+
460
+ /**
461
+ * Utility function to constrain the type of a lookup result
462
+ * @param result the result of a lookup
463
+ * @returns {Uint8Array | undefined} the value if the lookup was found, `undefined` otherwise
464
+ */
465
+ export function lookupResultToBuffer(result: LookupResult): Uint8Array | undefined {
466
+ if (result.status !== LookupPathStatus.Found) {
467
+ return undefined;
468
+ }
469
+
470
+ if (result.value instanceof Uint8Array) {
471
+ return result.value;
472
+ }
473
+
474
+ return undefined;
475
+ }
476
+
477
+ /**
478
+ * @param t The hash tree to reconstruct
479
+ */
480
+ export async function reconstruct(t: HashTree): Promise<Uint8Array> {
481
+ switch (t[0]) {
482
+ case NodeType.Empty:
483
+ return sha256(domain_sep('ic-hashtree-empty'));
484
+ case NodeType.Pruned:
485
+ return t[1];
486
+ case NodeType.Leaf:
487
+ return sha256(concatBytes(domain_sep('ic-hashtree-leaf'), t[1]));
488
+ case NodeType.Labeled:
489
+ return sha256(concatBytes(domain_sep('ic-hashtree-labeled'), t[1], await reconstruct(t[2])));
490
+ case NodeType.Fork:
491
+ return sha256(
492
+ concatBytes(
493
+ domain_sep('ic-hashtree-fork'),
494
+ await reconstruct(t[1]),
495
+ await reconstruct(t[2]),
496
+ ),
497
+ );
498
+ default:
499
+ throw UNREACHABLE_ERROR;
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Creates a domain separator for hashing by encoding the input string
505
+ * with its length as a prefix.
506
+ * @param s - The input string to encode.
507
+ * @returns A Uint8Array containing the encoded domain separator.
508
+ */
509
+ export function domain_sep(s: string): Uint8Array {
510
+ const len = new Uint8Array([s.length]);
511
+ const str = new TextEncoder().encode(s);
512
+ return concatBytes(len, str);
513
+ }
514
+
515
+ function pathToLabel(path: NodePath): NodeLabel {
516
+ return (typeof path[0] === 'string' ? utf8ToBytes(path[0]) : path[0]) as NodeLabel;
517
+ }
518
+
519
+ export enum LookupPathStatus {
520
+ Unknown = 'Unknown',
521
+ Absent = 'Absent',
522
+ Found = 'Found',
523
+ Error = 'Error',
524
+ }
525
+
526
+ export interface LookupPathResultAbsent {
527
+ status: LookupPathStatus.Absent;
528
+ }
529
+
530
+ export interface LookupPathResultUnknown {
531
+ status: LookupPathStatus.Unknown;
532
+ }
533
+
534
+ export interface LookupPathResultFound {
535
+ status: LookupPathStatus.Found;
536
+ value: Uint8Array;
537
+ }
538
+
539
+ export interface LookupPathResultError {
540
+ status: LookupPathStatus.Error;
541
+ }
542
+
543
+ export type LookupResult =
544
+ | LookupPathResultAbsent
545
+ | LookupPathResultUnknown
546
+ | LookupPathResultFound
547
+ | LookupPathResultError;
548
+
549
+ export enum LookupSubtreeStatus {
550
+ Absent = 'Absent',
551
+ Unknown = 'Unknown',
552
+ Found = 'Found',
553
+ }
554
+
555
+ export interface LookupSubtreeResultAbsent {
556
+ status: LookupSubtreeStatus.Absent;
557
+ }
558
+
559
+ export interface LookupSubtreeResultUnknown {
560
+ status: LookupSubtreeStatus.Unknown;
561
+ }
562
+
563
+ export interface LookupSubtreeResultFound {
564
+ status: LookupSubtreeStatus.Found;
565
+ value: HashTree;
566
+ }
567
+
568
+ export type SubtreeLookupResult =
569
+ | LookupSubtreeResultAbsent
570
+ | LookupSubtreeResultUnknown
571
+ | LookupSubtreeResultFound;
572
+
573
+ export enum LookupLabelStatus {
574
+ Absent = 'Absent',
575
+ Unknown = 'Unknown',
576
+ Found = 'Found',
577
+ Less = 'Less',
578
+ Greater = 'Greater',
579
+ }
580
+
581
+ export interface LookupLabelResultAbsent {
582
+ status: LookupLabelStatus.Absent;
583
+ }
584
+
585
+ export interface LookupLabelResultUnknown {
586
+ status: LookupLabelStatus.Unknown;
587
+ }
588
+
589
+ export interface LookupLabelResultFound {
590
+ status: LookupLabelStatus.Found;
591
+ value: HashTree;
592
+ }
593
+
594
+ export interface LookupLabelResultGreater {
595
+ status: LookupLabelStatus.Greater;
596
+ }
597
+
598
+ export interface LookupLabelResultLess {
599
+ status: LookupLabelStatus.Less;
600
+ }
601
+
602
+ export type LabelLookupResult =
603
+ | LookupLabelResultAbsent
604
+ | LookupLabelResultUnknown
605
+ | LookupLabelResultFound
606
+ | LookupLabelResultGreater
607
+ | LookupLabelResultLess;
608
+
609
+ /**
610
+ * Lookup a path in a tree. If the path is a subtree, use {@link lookup_subtree} instead.
611
+ * @param path the path to look up
612
+ * @param tree the tree to search
613
+ * @returns {LookupResult} the result of the lookup
614
+ */
615
+ export function lookup_path(path: NodePath, tree: HashTree): LookupResult {
616
+ if (path.length === 0) {
617
+ switch (tree[0]) {
618
+ case NodeType.Empty: {
619
+ return {
620
+ status: LookupPathStatus.Absent,
621
+ };
622
+ }
623
+
624
+ case NodeType.Leaf: {
625
+ if (!tree[1]) {
626
+ throw UnknownError.fromCode(
627
+ new HashTreeDecodeErrorCode('Invalid tree structure for leaf'),
628
+ );
629
+ }
630
+
631
+ if (tree[1] instanceof Uint8Array) {
632
+ return {
633
+ status: LookupPathStatus.Found,
634
+ value: tree[1].slice(tree[1].byteOffset, tree[1].byteLength + tree[1].byteOffset),
635
+ };
636
+ }
637
+
638
+ throw UNREACHABLE_ERROR;
639
+ }
640
+
641
+ case NodeType.Pruned: {
642
+ return {
643
+ status: LookupPathStatus.Unknown,
644
+ };
645
+ }
646
+
647
+ case NodeType.Labeled:
648
+ case NodeType.Fork: {
649
+ return {
650
+ status: LookupPathStatus.Error,
651
+ };
652
+ }
653
+
654
+ default: {
655
+ throw UNREACHABLE_ERROR;
656
+ }
657
+ }
658
+ }
659
+
660
+ const label = pathToLabel(path);
661
+ const lookupResult = find_label(label, tree);
662
+
663
+ switch (lookupResult.status) {
664
+ case LookupLabelStatus.Found: {
665
+ return lookup_path(path.slice(1), lookupResult.value);
666
+ }
667
+
668
+ case LookupLabelStatus.Absent:
669
+ case LookupLabelStatus.Greater:
670
+ case LookupLabelStatus.Less: {
671
+ return {
672
+ status: LookupPathStatus.Absent,
673
+ };
674
+ }
675
+
676
+ case LookupLabelStatus.Unknown: {
677
+ return {
678
+ status: LookupPathStatus.Unknown,
679
+ };
680
+ }
681
+
682
+ default: {
683
+ throw UNREACHABLE_ERROR;
684
+ }
685
+ }
686
+ }
687
+
688
+ /**
689
+ * Lookup a subtree in a tree.
690
+ * @param path the path to look up
691
+ * @param tree the tree to search
692
+ * @returns {SubtreeLookupResult} the result of the lookup
693
+ */
694
+ export function lookup_subtree(path: NodePath, tree: HashTree): SubtreeLookupResult {
695
+ if (path.length === 0) {
696
+ return {
697
+ status: LookupSubtreeStatus.Found,
698
+ value: tree,
699
+ };
700
+ }
701
+
702
+ const label = pathToLabel(path);
703
+ const lookupResult = find_label(label, tree);
704
+
705
+ switch (lookupResult.status) {
706
+ case LookupLabelStatus.Found: {
707
+ return lookup_subtree(path.slice(1), lookupResult.value);
708
+ }
709
+
710
+ case LookupLabelStatus.Unknown: {
711
+ return {
712
+ status: LookupSubtreeStatus.Unknown,
713
+ };
714
+ }
715
+
716
+ case LookupLabelStatus.Absent:
717
+ case LookupLabelStatus.Greater:
718
+ case LookupLabelStatus.Less: {
719
+ return {
720
+ status: LookupSubtreeStatus.Absent,
721
+ };
722
+ }
723
+
724
+ default: {
725
+ throw UNREACHABLE_ERROR;
726
+ }
727
+ }
728
+ }
729
+
730
+ /**
731
+ * If the tree is a fork, flatten it into an array of trees
732
+ * @param {HashTree} t the tree to flatten
733
+ * @returns {HashTree[]} the flattened tree
734
+ */
735
+ export function flatten_forks(t: HashTree): Array<LabeledHashTree | LeafHashTree | PrunedHashTree> {
736
+ switch (t[0]) {
737
+ case NodeType.Empty:
738
+ return [];
739
+ case NodeType.Fork:
740
+ return flatten_forks(t[1]).concat(flatten_forks(t[2]));
741
+ default:
742
+ return [t];
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Find a label in a tree
748
+ * @param label the label to find
749
+ * @param tree the tree to search
750
+ * @returns {LabelLookupResult} the result of the label lookup
751
+ */
752
+ export function find_label(label: NodeLabel, tree: HashTree): LabelLookupResult {
753
+ switch (tree[0]) {
754
+ // if we have a labelled node, compare the node's label to the one we are
755
+ // looking for
756
+ case NodeType.Labeled:
757
+ // if the label we're searching for is greater than this node's label,
758
+ // we need to keep searching
759
+ if (isBufferGreaterThan(label, tree[1])) {
760
+ return {
761
+ status: LookupLabelStatus.Greater,
762
+ };
763
+ }
764
+
765
+ // if the label we're searching for is equal this node's label, we can
766
+ // stop searching and return the found node
767
+ if (uint8Equals(label, tree[1])) {
768
+ return {
769
+ status: LookupLabelStatus.Found,
770
+ value: tree[2],
771
+ };
772
+ }
773
+
774
+ // if the label we're searching for is not greater than or equal to this
775
+ // node's label, then it's less than this node's label, and we can stop
776
+ // searching because we've looked too far
777
+ return {
778
+ status: LookupLabelStatus.Less,
779
+ };
780
+
781
+ // if we have a fork node, we need to search both sides, starting with the left
782
+ case NodeType.Fork: {
783
+ // search in the left node
784
+ const leftLookupResult = find_label(label, tree[1]);
785
+
786
+ switch (leftLookupResult.status) {
787
+ // if the label we're searching for is greater than the left node lookup,
788
+ // we need to search the right node
789
+ case LookupLabelStatus.Greater: {
790
+ const rightLookupResult = find_label(label, tree[2]);
791
+
792
+ // if the label we're searching for is less than the right node lookup,
793
+ // then we can stop searching and say that the label is provably Absent
794
+ if (rightLookupResult.status === LookupLabelStatus.Less) {
795
+ return {
796
+ status: LookupLabelStatus.Absent,
797
+ };
798
+ }
799
+
800
+ // if the label we're searching for is less than or equal to the right
801
+ // node lookup, then we let the caller handle it
802
+ return rightLookupResult;
803
+ }
804
+
805
+ // if the left node returns an uncertain result, we need to search the
806
+ // right node
807
+ case LookupLabelStatus.Unknown: {
808
+ const rightLookupResult = find_label(label, tree[2]);
809
+
810
+ // if the label we're searching for is less than the right node lookup,
811
+ // then we also need to return an uncertain result
812
+ if (rightLookupResult.status === LookupLabelStatus.Less) {
813
+ return {
814
+ status: LookupLabelStatus.Unknown,
815
+ };
816
+ }
817
+
818
+ // if the label we're searching for is less than or equal to the right
819
+ // node lookup, then we let the caller handle it
820
+ return rightLookupResult;
821
+ }
822
+
823
+ // if the label we're searching for is not greater than the left node
824
+ // lookup, or the result is not uncertain, we stop searching and return
825
+ // whatever the result of the left node lookup was, which can be either
826
+ // Found or Absent
827
+ default: {
828
+ return leftLookupResult;
829
+ }
830
+ }
831
+ }
832
+
833
+ // if we encounter a Pruned node, we can't know for certain if the label
834
+ // we're searching for is present or not
835
+ case NodeType.Pruned:
836
+ return {
837
+ status: LookupLabelStatus.Unknown,
838
+ };
839
+
840
+ // if the current node is Empty, or a Leaf, we can stop searching because
841
+ // we know for sure that the label we're searching for is not present
842
+ default:
843
+ return {
844
+ status: LookupLabelStatus.Absent,
845
+ };
846
+ }
847
+ }
848
+
849
+ /**
850
+ * Ported from https://github.com/dfinity/response-verification/blob/a4b8b46bcf93f44ac30b5698e60bfd245e33ad4e/packages/ic-certification/src/hash_tree/mod.rs#L527-L541.
851
+ * @param path the path to prepend to the paths of the tree
852
+ * @param tree the tree to list the paths of
853
+ * @returns the paths of the tree
854
+ */
855
+ function list_paths(path: Array<NodeLabel>, tree: HashTree): Array<Array<NodeLabel>> {
856
+ switch (tree[0]) {
857
+ case NodeType.Empty | NodeType.Pruned: {
858
+ return [];
859
+ }
860
+ case NodeType.Leaf: {
861
+ return [path];
862
+ }
863
+ case NodeType.Fork: {
864
+ return list_paths(path, tree[1]).concat(list_paths(path, tree[2]));
865
+ }
866
+ case NodeType.Labeled: {
867
+ const label = tree[1];
868
+ const subtree = tree[2];
869
+ const pathWithLabel = [...path, label];
870
+ return list_paths(pathWithLabel, subtree);
871
+ }
872
+ default: {
873
+ throw UNREACHABLE_ERROR;
874
+ }
875
+ }
876
+ }
877
+
878
+ export type CheckCanisterRangesParams = {
879
+ canisterId: Principal;
880
+ subnetId: Principal;
881
+ tree: HashTree;
882
+ };
883
+
884
+ /**
885
+ * Canister ranges in the form of an array of [start, end] principal tuples,
886
+ * usually decoded from the certificate.
887
+ */
888
+ export type CanisterRanges = Array<[Principal, Principal]>;
889
+
890
+ /**
891
+ * Check if a canister ID falls within the canister ranges of a given subnet
892
+ * @param params the parameters with which to check the canister ranges
893
+ * @param params.canisterId the canister ID to check
894
+ * @param params.subnetId the subnet ID from which to check the canister ranges
895
+ * @param params.tree the hash tree in which to lookup the subnet's canister ranges
896
+ * @returns {boolean} `true` if the canister is in the range, `false` otherwise
897
+ */
898
+ export function check_canister_ranges(params: CheckCanisterRangesParams): boolean {
899
+ const rangesLookupValue = lookupCanisterRanges(params);
900
+ const ranges = decodeCanisterRanges(rangesLookupValue);
901
+
902
+ const { canisterId } = params;
903
+ const canisterInRange = ranges.some(r => r[0].ltEq(canisterId) && r[1].gtEq(canisterId));
904
+ return canisterInRange;
905
+ }
906
+
907
+ /**
908
+ * Lookup the canister ranges using the `/canister_ranges/<subnet_id>/<ranges>` path.
909
+ * Certificates returned by `/api/v4/canister/<effective_canister_id>/call`
910
+ * and `/api/v3/canister/<effective_canister_id>/read_state` use this path.
911
+ *
912
+ * If the new lookup is not found, it tries the fallback lookup with {@link lookupCanisterRangesFallback}.
913
+ * @param params the parameters with which to lookup the canister ranges
914
+ * @param params.subnetId the subnet ID to lookup the canister ranges for
915
+ * @param params.tree the tree to search
916
+ * @param params.canisterId the canister ID to check
917
+ * @returns the encoded canister ranges. Use {@link decodeCanisterRanges} to decode them.
918
+ * @see https://internetcomputer.org/docs/references/ic-interface-spec#http-read-state
919
+ * @see https://internetcomputer.org/docs/references/ic-interface-spec#state-tree-canister-ranges
920
+ */
921
+ export function lookupCanisterRanges(params: CheckCanisterRangesParams): Uint8Array {
922
+ const { subnetId, tree, canisterId } = params;
923
+
924
+ const canisterRangeShardsLookup = lookup_subtree(
925
+ ['canister_ranges', subnetId.toUint8Array()],
926
+ tree,
927
+ );
928
+ if (canisterRangeShardsLookup.status !== LookupSubtreeStatus.Found) {
929
+ return lookupCanisterRangesFallback(subnetId, tree);
930
+ }
931
+
932
+ const canisterRangeShards = canisterRangeShardsLookup.value;
933
+
934
+ const shardPaths = getCanisterRangeShardPaths(canisterRangeShards);
935
+ if (shardPaths.length === 0) {
936
+ throw ProtocolError.fromCode(new CertificateNotAuthorizedErrorCode(canisterId, subnetId));
937
+ }
938
+ shardPaths.sort(uint8Compare);
939
+
940
+ const shardDivision = getCanisterRangeShardPartitionPoint(shardPaths, canisterId);
941
+ const maxPotentialShard = shardPaths[shardDivision];
942
+
943
+ const canisterRange = getCanisterRangeFromShards(maxPotentialShard, canisterRangeShards);
944
+
945
+ return canisterRange;
946
+ }
947
+
948
+ /**
949
+ * Lookup the canister ranges using the `/subnet/<subnet_id>/canister_ranges` path.
950
+ * Certificates returned by `/api/v3/canister/<effective_canister_id>/call`
951
+ * and `/api/v2/canister/<effective_canister_id>/read_state` use this path.
952
+ * @param subnetId the subnet ID to lookup the canister ranges for
953
+ * @param tree the tree to search
954
+ * @returns the encoded canister ranges. Use {@link decodeCanisterRanges} to decode them.
955
+ * @see https://internetcomputer.org/docs/references/ic-interface-spec#http-read-state
956
+ */
957
+ export function lookupCanisterRangesFallback(subnetId: Principal, tree: HashTree): Uint8Array {
958
+ const lookupResult = lookup_path(['subnet', subnetId.toUint8Array(), 'canister_ranges'], tree);
959
+ if (lookupResult.status !== LookupPathStatus.Found) {
960
+ throw ProtocolError.fromCode(
961
+ new LookupErrorCode(
962
+ `Could not find canister ranges for subnet ${subnetId.toText()}`,
963
+ lookupResult.status,
964
+ ),
965
+ );
966
+ }
967
+ return lookupResult.value;
968
+ }
969
+
970
+ /**
971
+ * Decode canister ranges from CBOR-encoded buffer
972
+ * @param lookupValue the CBOR-encoded value read from the certificate
973
+ * @returns an array of canister range tuples [start, end]
974
+ */
975
+ export function decodeCanisterRanges(lookupValue: Uint8Array): CanisterRanges {
976
+ const ranges_arr = cbor.decode<Array<[Uint8Array, Uint8Array]>>(lookupValue);
977
+ const ranges: CanisterRanges = ranges_arr.map(v => [
978
+ Principal.fromUint8Array(v[0]),
979
+ Principal.fromUint8Array(v[1]),
980
+ ]);
981
+ return ranges;
982
+ }
983
+
984
+ function getCanisterRangeShardPaths(canisterRangeShards: HashTree): Array<NodeLabel> {
985
+ const shardPaths: Array<NodeLabel> = [];
986
+
987
+ for (const path of list_paths([], canisterRangeShards)) {
988
+ const firstLabel = path[0];
989
+ if (!firstLabel) {
990
+ throw ProtocolError.fromCode(new CertificateVerificationErrorCode('Path is invalid'));
991
+ }
992
+ shardPaths.push(firstLabel);
993
+ }
994
+
995
+ return shardPaths;
996
+ }
997
+
998
+ /**
999
+ * Finds the partition point that divides shard paths into two groups based on canister ID comparison.
1000
+ * Uses binary search to partition the array where:
1001
+ * - Elements at indices [0, partitionPoint) have values >= canisterId
1002
+ * - Elements at indices [partitionPoint, length) have values < canisterId
1003
+ * @param shardPaths Sorted array of shard paths to search through
1004
+ * @param canisterId The canister ID to compare against
1005
+ * @returns The index of the first shard that is less than the canister ID, or shardPaths.length if all shards are >= canisterId
1006
+ */
1007
+ function getCanisterRangeShardPartitionPoint(
1008
+ shardPaths: Array<NodeLabel>,
1009
+ canisterId: Principal,
1010
+ ): number {
1011
+ const canisterIdBytes = canisterId.toUint8Array();
1012
+ let left = 0;
1013
+ let right = shardPaths.length;
1014
+
1015
+ // Binary search for the first element where shard < canisterId
1016
+ while (left < right) {
1017
+ const mid = Math.floor((left + right) / 2);
1018
+ if (uint8Compare(shardPaths[mid], canisterIdBytes) <= 0) {
1019
+ // Found an element <= canisterId, search left half for earlier occurrence
1020
+ right = mid;
1021
+ } else {
1022
+ // Element is > canisterId, search right half
1023
+ left = mid + 1;
1024
+ }
1025
+ }
1026
+
1027
+ return left;
1028
+ }
1029
+
1030
+ function getCanisterRangeFromShards(
1031
+ maxShardPath: NodeLabel,
1032
+ canisterRangeShards: HashTree,
1033
+ ): Uint8Array {
1034
+ const canisterRange = lookup_path([maxShardPath], canisterRangeShards);
1035
+ if (canisterRange.status !== LookupPathStatus.Found) {
1036
+ throw ProtocolError.fromCode(
1037
+ new LookupErrorCode(
1038
+ `Could not find canister range for shard ${maxShardPath.toString()}`,
1039
+ canisterRange.status,
1040
+ ),
1041
+ );
1042
+ }
1043
+ return canisterRange.value;
1044
+ }
1045
+
1046
+ /**
1047
+ * Get the subnet ID from a certificate
1048
+ * If the certificate has a delegation, it returns the subnet ID from the delegation.
1049
+ * If the certificate has no delegation, it returns the root subnet ID.
1050
+ * @param certificate the certificate to get the subnet ID from
1051
+ * @param rootKey the root key to use to get the subnet ID
1052
+ * @returns the subnet ID
1053
+ */
1054
+ export function getSubnetIdFromCertificate(certificate: Cert, rootKey: Uint8Array): Principal {
1055
+ if (certificate.delegation) {
1056
+ return Principal.fromUint8Array(certificate.delegation.subnet_id);
1057
+ }
1058
+ // If certificate has no delegation, it comes from the root subnet
1059
+ return Principal.selfAuthenticating(rootKey);
1060
+ }