@bopen-io/wallet-toolbox 1.7.18

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 (390) hide show
  1. package/.claude/settings.local.json +10 -0
  2. package/.env.template +22 -0
  3. package/.github/ISSUE_TEMPLATE/bug_report.md +40 -0
  4. package/.github/ISSUE_TEMPLATE/discussion.md +24 -0
  5. package/.github/pull_request_template.md +22 -0
  6. package/.github/workflows/push.yaml +145 -0
  7. package/.prettierrc +10 -0
  8. package/CHANGELOG.md +280 -0
  9. package/CONTRIBUTING.md +89 -0
  10. package/README.md +43 -0
  11. package/docs/README.md +85 -0
  12. package/docs/client.md +19627 -0
  13. package/docs/monitor.md +953 -0
  14. package/docs/open-rpc/index.html +46 -0
  15. package/docs/services.md +6377 -0
  16. package/docs/setup.md +1268 -0
  17. package/docs/storage.md +5367 -0
  18. package/docs/wallet.md +19626 -0
  19. package/jest.config.ts +25 -0
  20. package/license.md +28 -0
  21. package/out/tsconfig.all.tsbuildinfo +1 -0
  22. package/package.json +63 -0
  23. package/src/CWIStyleWalletManager.ts +1999 -0
  24. package/src/Setup.ts +579 -0
  25. package/src/SetupClient.ts +322 -0
  26. package/src/SetupWallet.ts +108 -0
  27. package/src/SimpleWalletManager.ts +526 -0
  28. package/src/Wallet.ts +1169 -0
  29. package/src/WalletAuthenticationManager.ts +153 -0
  30. package/src/WalletLogger.ts +213 -0
  31. package/src/WalletPermissionsManager.ts +3660 -0
  32. package/src/WalletSettingsManager.ts +114 -0
  33. package/src/__tests/CWIStyleWalletManager.test.d.ts.map +1 -0
  34. package/src/__tests/CWIStyleWalletManager.test.js.map +1 -0
  35. package/src/__tests/CWIStyleWalletManager.test.ts +675 -0
  36. package/src/__tests/WalletPermissionsManager.callbacks.test.ts +323 -0
  37. package/src/__tests/WalletPermissionsManager.checks.test.ts +844 -0
  38. package/src/__tests/WalletPermissionsManager.encryption.test.ts +412 -0
  39. package/src/__tests/WalletPermissionsManager.fixtures.ts +307 -0
  40. package/src/__tests/WalletPermissionsManager.flows.test.ts +462 -0
  41. package/src/__tests/WalletPermissionsManager.initialization.test.ts +300 -0
  42. package/src/__tests/WalletPermissionsManager.pmodules.test.ts +798 -0
  43. package/src/__tests/WalletPermissionsManager.proxying.test.ts +724 -0
  44. package/src/__tests/WalletPermissionsManager.tokens.test.ts +503 -0
  45. package/src/index.all.ts +27 -0
  46. package/src/index.client.ts +25 -0
  47. package/src/index.mobile.ts +21 -0
  48. package/src/index.ts +1 -0
  49. package/src/monitor/Monitor.ts +412 -0
  50. package/src/monitor/MonitorDaemon.ts +188 -0
  51. package/src/monitor/README.md +3 -0
  52. package/src/monitor/__test/MonitorDaemon.man.test.ts +45 -0
  53. package/src/monitor/tasks/TaskCheckForProofs.ts +243 -0
  54. package/src/monitor/tasks/TaskCheckNoSends.ts +73 -0
  55. package/src/monitor/tasks/TaskClock.ts +33 -0
  56. package/src/monitor/tasks/TaskFailAbandoned.ts +54 -0
  57. package/src/monitor/tasks/TaskMonitorCallHistory.ts +26 -0
  58. package/src/monitor/tasks/TaskNewHeader.ts +93 -0
  59. package/src/monitor/tasks/TaskPurge.ts +68 -0
  60. package/src/monitor/tasks/TaskReorg.ts +89 -0
  61. package/src/monitor/tasks/TaskReviewStatus.ts +48 -0
  62. package/src/monitor/tasks/TaskSendWaiting.ts +122 -0
  63. package/src/monitor/tasks/TaskSyncWhenIdle.ts +26 -0
  64. package/src/monitor/tasks/TaskUnFail.ts +151 -0
  65. package/src/monitor/tasks/WalletMonitorTask.ts +47 -0
  66. package/src/sdk/CertOpsWallet.ts +18 -0
  67. package/src/sdk/PrivilegedKeyManager.ts +372 -0
  68. package/src/sdk/README.md +13 -0
  69. package/src/sdk/WERR_errors.ts +234 -0
  70. package/src/sdk/WalletError.ts +170 -0
  71. package/src/sdk/WalletErrorFromJson.ts +80 -0
  72. package/src/sdk/WalletServices.interfaces.ts +700 -0
  73. package/src/sdk/WalletSigner.interfaces.ts +11 -0
  74. package/src/sdk/WalletStorage.interfaces.ts +606 -0
  75. package/src/sdk/__test/CertificateLifeCycle.test.ts +131 -0
  76. package/src/sdk/__test/PrivilegedKeyManager.test.ts +738 -0
  77. package/src/sdk/__test/WalletError.test.ts +318 -0
  78. package/src/sdk/__test/validationHelpers.test.ts +21 -0
  79. package/src/sdk/index.ts +10 -0
  80. package/src/sdk/types.ts +226 -0
  81. package/src/services/README.md +11 -0
  82. package/src/services/ServiceCollection.ts +248 -0
  83. package/src/services/Services.ts +603 -0
  84. package/src/services/__tests/ARC.man.test.ts +123 -0
  85. package/src/services/__tests/ARC.timeout.man.test.ts +79 -0
  86. package/src/services/__tests/ArcGorillaPool.man.test.ts +108 -0
  87. package/src/services/__tests/arcServices.test.ts +8 -0
  88. package/src/services/__tests/bitrails.test.ts +56 -0
  89. package/src/services/__tests/getMerklePath.test.ts +15 -0
  90. package/src/services/__tests/getRawTx.test.ts +13 -0
  91. package/src/services/__tests/postBeef.test.ts +104 -0
  92. package/src/services/__tests/verifyBeef.test.ts +50 -0
  93. package/src/services/chaintracker/BHServiceClient.ts +212 -0
  94. package/src/services/chaintracker/ChaintracksChainTracker.ts +71 -0
  95. package/src/services/chaintracker/__tests/ChaintracksChainTracker.test.ts +33 -0
  96. package/src/services/chaintracker/__tests/ChaintracksServiceClient.test.ts +29 -0
  97. package/src/services/chaintracker/chaintracks/Api/BlockHeaderApi.ts +72 -0
  98. package/src/services/chaintracker/chaintracks/Api/BulkIngestorApi.ts +83 -0
  99. package/src/services/chaintracker/chaintracks/Api/BulkStorageApi.ts +92 -0
  100. package/src/services/chaintracker/chaintracks/Api/ChaintracksApi.ts +64 -0
  101. package/src/services/chaintracker/chaintracks/Api/ChaintracksClientApi.ts +189 -0
  102. package/src/services/chaintracker/chaintracks/Api/ChaintracksFetchApi.ts +18 -0
  103. package/src/services/chaintracker/chaintracks/Api/ChaintracksFsApi.ts +58 -0
  104. package/src/services/chaintracker/chaintracks/Api/ChaintracksStorageApi.ts +386 -0
  105. package/src/services/chaintracker/chaintracks/Api/LiveIngestorApi.ts +25 -0
  106. package/src/services/chaintracker/chaintracks/Chaintracks.ts +609 -0
  107. package/src/services/chaintracker/chaintracks/ChaintracksService.ts +199 -0
  108. package/src/services/chaintracker/chaintracks/ChaintracksServiceClient.ts +154 -0
  109. package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorBase.ts +176 -0
  110. package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDN.ts +174 -0
  111. package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDNBabbage.ts +18 -0
  112. package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorWhatsOnChainCdn.ts +113 -0
  113. package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorWhatsOnChainWs.ts +81 -0
  114. package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorBase.ts +86 -0
  115. package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorTeranodeP2P.ts +59 -0
  116. package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorWhatsOnChainPoll.ts +104 -0
  117. package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorWhatsOnChainWs.ts +66 -0
  118. package/src/services/chaintracker/chaintracks/Ingest/WhatsOnChainIngestorWs.ts +566 -0
  119. package/src/services/chaintracker/chaintracks/Ingest/WhatsOnChainServices.ts +219 -0
  120. package/src/services/chaintracker/chaintracks/Ingest/__tests/BulkIngestorCDNBabbage.test.ts +54 -0
  121. package/src/services/chaintracker/chaintracks/Ingest/__tests/LiveIngestorWhatsOnChainPoll.test.ts +33 -0
  122. package/src/services/chaintracker/chaintracks/Ingest/__tests/WhatsOnChainServices.test.ts +124 -0
  123. package/src/services/chaintracker/chaintracks/Storage/BulkStorageBase.ts +92 -0
  124. package/src/services/chaintracker/chaintracks/Storage/ChaintracksKnexMigrations.ts +104 -0
  125. package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageBase.ts +382 -0
  126. package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageIdb.ts +574 -0
  127. package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageKnex.ts +438 -0
  128. package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageMemory.ts +29 -0
  129. package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageNoDb.ts +304 -0
  130. package/src/services/chaintracker/chaintracks/Storage/__tests/ChaintracksStorageIdb.test.ts +102 -0
  131. package/src/services/chaintracker/chaintracks/Storage/__tests/ChaintracksStorageKnex.test.ts +45 -0
  132. package/src/services/chaintracker/chaintracks/__tests/Chaintracks.test.ts +77 -0
  133. package/src/services/chaintracker/chaintracks/__tests/ChaintracksClientApi.test.ts +192 -0
  134. package/src/services/chaintracker/chaintracks/__tests/LocalCdnServer.ts +75 -0
  135. package/src/services/chaintracker/chaintracks/__tests/createIdbChaintracks.test.ts +62 -0
  136. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNetBlockHeaders.json +1 -0
  137. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_0.headers +0 -0
  138. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_1.headers +0 -0
  139. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_2.headers +0 -0
  140. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_3.headers +0 -0
  141. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNetBlockHeaders.json +1 -0
  142. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_0.headers +0 -0
  143. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_1.headers +0 -0
  144. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_2.headers +0 -0
  145. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_3.headers +0 -0
  146. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNetBlockHeaders.json +1 -0
  147. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_0.headers +0 -0
  148. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_1.headers +0 -0
  149. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_2.headers +0 -0
  150. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_3.headers +0 -0
  151. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNetBlockHeaders.json +1 -0
  152. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_0.headers +0 -0
  153. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_1.headers +0 -0
  154. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_2.headers +0 -0
  155. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_3.headers +0 -0
  156. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_4.headers +0 -0
  157. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNetBlockHeaders.json +1 -0
  158. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_0.headers +0 -0
  159. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_1.headers +0 -0
  160. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_2.headers +0 -0
  161. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_3.headers +0 -0
  162. package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_4.headers +0 -0
  163. package/src/services/chaintracker/chaintracks/createDefaultIdbChaintracksOptions.ts +92 -0
  164. package/src/services/chaintracker/chaintracks/createDefaultKnexChaintracksOptions.ts +111 -0
  165. package/src/services/chaintracker/chaintracks/createDefaultNoDbChaintracksOptions.ts +91 -0
  166. package/src/services/chaintracker/chaintracks/createIdbChaintracks.ts +60 -0
  167. package/src/services/chaintracker/chaintracks/createKnexChaintracks.ts +65 -0
  168. package/src/services/chaintracker/chaintracks/createNoDbChaintracks.ts +60 -0
  169. package/src/services/chaintracker/chaintracks/index.all.ts +12 -0
  170. package/src/services/chaintracker/chaintracks/index.client.ts +4 -0
  171. package/src/services/chaintracker/chaintracks/index.mobile.ts +37 -0
  172. package/src/services/chaintracker/chaintracks/util/BulkFileDataManager.ts +975 -0
  173. package/src/services/chaintracker/chaintracks/util/BulkFileDataReader.ts +60 -0
  174. package/src/services/chaintracker/chaintracks/util/BulkFilesReader.ts +336 -0
  175. package/src/services/chaintracker/chaintracks/util/BulkHeaderFile.ts +247 -0
  176. package/src/services/chaintracker/chaintracks/util/ChaintracksFetch.ts +69 -0
  177. package/src/services/chaintracker/chaintracks/util/ChaintracksFs.ts +141 -0
  178. package/src/services/chaintracker/chaintracks/util/HeightRange.ts +153 -0
  179. package/src/services/chaintracker/chaintracks/util/SingleWriterMultiReaderLock.ts +76 -0
  180. package/src/services/chaintracker/chaintracks/util/__tests/BulkFileDataManager.test.ts +304 -0
  181. package/src/services/chaintracker/chaintracks/util/__tests/ChaintracksFetch.test.ts +60 -0
  182. package/src/services/chaintracker/chaintracks/util/__tests/HeightRange.test.ts +67 -0
  183. package/src/services/chaintracker/chaintracks/util/__tests/SingleWriterMultiReaderLock.test.ts +49 -0
  184. package/src/services/chaintracker/chaintracks/util/blockHeaderUtilities.ts +573 -0
  185. package/src/services/chaintracker/chaintracks/util/dirtyHashes.ts +29 -0
  186. package/src/services/chaintracker/chaintracks/util/validBulkHeaderFilesByFileHash.ts +432 -0
  187. package/src/services/chaintracker/index.all.ts +4 -0
  188. package/src/services/chaintracker/index.client.ts +4 -0
  189. package/src/services/chaintracker/index.mobile.ts +4 -0
  190. package/src/services/createDefaultWalletServicesOptions.ts +77 -0
  191. package/src/services/index.ts +1 -0
  192. package/src/services/processingErrors/arcSuccessError.json +76 -0
  193. package/src/services/providers/ARC.ts +350 -0
  194. package/src/services/providers/Bitails.ts +256 -0
  195. package/src/services/providers/SdkWhatsOnChain.ts +83 -0
  196. package/src/services/providers/WhatsOnChain.ts +883 -0
  197. package/src/services/providers/__tests/WhatsOnChain.test.ts +242 -0
  198. package/src/services/providers/__tests/exchangeRates.test.ts +18 -0
  199. package/src/services/providers/exchangeRates.ts +265 -0
  200. package/src/services/providers/getBeefForTxid.ts +369 -0
  201. package/src/signer/README.md +5 -0
  202. package/src/signer/WalletSigner.ts +17 -0
  203. package/src/signer/methods/acquireDirectCertificate.ts +52 -0
  204. package/src/signer/methods/buildSignableTransaction.ts +183 -0
  205. package/src/signer/methods/completeSignedTransaction.ts +117 -0
  206. package/src/signer/methods/createAction.ts +172 -0
  207. package/src/signer/methods/internalizeAction.ts +106 -0
  208. package/src/signer/methods/proveCertificate.ts +43 -0
  209. package/src/signer/methods/signAction.ts +54 -0
  210. package/src/storage/README.md +14 -0
  211. package/src/storage/StorageIdb.ts +2304 -0
  212. package/src/storage/StorageKnex.ts +1425 -0
  213. package/src/storage/StorageProvider.ts +810 -0
  214. package/src/storage/StorageReader.ts +194 -0
  215. package/src/storage/StorageReaderWriter.ts +432 -0
  216. package/src/storage/StorageSyncReader.ts +34 -0
  217. package/src/storage/WalletStorageManager.ts +943 -0
  218. package/src/storage/__test/StorageIdb.test.ts +43 -0
  219. package/src/storage/__test/WalletStorageManager.test.ts +275 -0
  220. package/src/storage/__test/adminStats.man.test.ts +89 -0
  221. package/src/storage/__test/getBeefForTransaction.test.ts +385 -0
  222. package/src/storage/index.all.ts +11 -0
  223. package/src/storage/index.client.ts +7 -0
  224. package/src/storage/index.mobile.ts +6 -0
  225. package/src/storage/methods/ListActionsSpecOp.ts +70 -0
  226. package/src/storage/methods/ListOutputsSpecOp.ts +129 -0
  227. package/src/storage/methods/__test/GenerateChange/generateChangeSdk.test.ts +1057 -0
  228. package/src/storage/methods/__test/GenerateChange/randomValsUsed1.ts +20 -0
  229. package/src/storage/methods/__test/offsetKey.test.ts +274 -0
  230. package/src/storage/methods/attemptToPostReqsToNetwork.ts +389 -0
  231. package/src/storage/methods/createAction.ts +947 -0
  232. package/src/storage/methods/generateChange.ts +556 -0
  233. package/src/storage/methods/getBeefForTransaction.ts +139 -0
  234. package/src/storage/methods/getSyncChunk.ts +293 -0
  235. package/src/storage/methods/internalizeAction.ts +562 -0
  236. package/src/storage/methods/listActionsIdb.ts +183 -0
  237. package/src/storage/methods/listActionsKnex.ts +226 -0
  238. package/src/storage/methods/listCertificates.ts +73 -0
  239. package/src/storage/methods/listOutputsIdb.ts +203 -0
  240. package/src/storage/methods/listOutputsKnex.ts +263 -0
  241. package/src/storage/methods/offsetKey.ts +89 -0
  242. package/src/storage/methods/processAction.ts +420 -0
  243. package/src/storage/methods/purgeData.ts +251 -0
  244. package/src/storage/methods/purgeDataIdb.ts +10 -0
  245. package/src/storage/methods/reviewStatus.ts +101 -0
  246. package/src/storage/methods/reviewStatusIdb.ts +43 -0
  247. package/src/storage/methods/utils.Buffer.ts +33 -0
  248. package/src/storage/methods/utils.ts +56 -0
  249. package/src/storage/remoting/StorageClient.ts +567 -0
  250. package/src/storage/remoting/StorageMobile.ts +544 -0
  251. package/src/storage/remoting/StorageServer.ts +291 -0
  252. package/src/storage/remoting/__test/StorageClient.test.ts +113 -0
  253. package/src/storage/schema/KnexMigrations.ts +489 -0
  254. package/src/storage/schema/StorageIdbSchema.ts +150 -0
  255. package/src/storage/schema/entities/EntityBase.ts +210 -0
  256. package/src/storage/schema/entities/EntityCertificate.ts +188 -0
  257. package/src/storage/schema/entities/EntityCertificateField.ts +136 -0
  258. package/src/storage/schema/entities/EntityCommission.ts +148 -0
  259. package/src/storage/schema/entities/EntityOutput.ts +290 -0
  260. package/src/storage/schema/entities/EntityOutputBasket.ts +153 -0
  261. package/src/storage/schema/entities/EntityOutputTag.ts +121 -0
  262. package/src/storage/schema/entities/EntityOutputTagMap.ts +123 -0
  263. package/src/storage/schema/entities/EntityProvenTx.ts +319 -0
  264. package/src/storage/schema/entities/EntityProvenTxReq.ts +580 -0
  265. package/src/storage/schema/entities/EntitySyncState.ts +389 -0
  266. package/src/storage/schema/entities/EntityTransaction.ts +306 -0
  267. package/src/storage/schema/entities/EntityTxLabel.ts +121 -0
  268. package/src/storage/schema/entities/EntityTxLabelMap.ts +123 -0
  269. package/src/storage/schema/entities/EntityUser.ts +112 -0
  270. package/src/storage/schema/entities/MergeEntity.ts +73 -0
  271. package/src/storage/schema/entities/__tests/CertificateFieldTests.test.ts +353 -0
  272. package/src/storage/schema/entities/__tests/CertificateTests.test.ts +354 -0
  273. package/src/storage/schema/entities/__tests/CommissionTests.test.ts +371 -0
  274. package/src/storage/schema/entities/__tests/OutputBasketTests.test.ts +278 -0
  275. package/src/storage/schema/entities/__tests/OutputTagMapTests.test.ts +242 -0
  276. package/src/storage/schema/entities/__tests/OutputTagTests.test.ts +288 -0
  277. package/src/storage/schema/entities/__tests/OutputTests.test.ts +464 -0
  278. package/src/storage/schema/entities/__tests/ProvenTxReqTests.test.ts +340 -0
  279. package/src/storage/schema/entities/__tests/ProvenTxTests.test.ts +504 -0
  280. package/src/storage/schema/entities/__tests/SyncStateTests.test.ts +288 -0
  281. package/src/storage/schema/entities/__tests/TransactionTests.test.ts +604 -0
  282. package/src/storage/schema/entities/__tests/TxLabelMapTests.test.ts +361 -0
  283. package/src/storage/schema/entities/__tests/TxLabelTests.test.ts +198 -0
  284. package/src/storage/schema/entities/__tests/stampLogTests.test.ts +90 -0
  285. package/src/storage/schema/entities/__tests/usersTests.test.ts +340 -0
  286. package/src/storage/schema/entities/index.ts +16 -0
  287. package/src/storage/schema/tables/TableCertificate.ts +21 -0
  288. package/src/storage/schema/tables/TableCertificateField.ts +12 -0
  289. package/src/storage/schema/tables/TableCommission.ts +13 -0
  290. package/src/storage/schema/tables/TableMonitorEvent.ts +9 -0
  291. package/src/storage/schema/tables/TableOutput.ts +64 -0
  292. package/src/storage/schema/tables/TableOutputBasket.ts +12 -0
  293. package/src/storage/schema/tables/TableOutputTag.ts +10 -0
  294. package/src/storage/schema/tables/TableOutputTagMap.ts +9 -0
  295. package/src/storage/schema/tables/TableProvenTx.ts +14 -0
  296. package/src/storage/schema/tables/TableProvenTxReq.ts +65 -0
  297. package/src/storage/schema/tables/TableSettings.ts +17 -0
  298. package/src/storage/schema/tables/TableSyncState.ts +18 -0
  299. package/src/storage/schema/tables/TableTransaction.ts +54 -0
  300. package/src/storage/schema/tables/TableTxLabel.ts +10 -0
  301. package/src/storage/schema/tables/TableTxLabelMap.ts +9 -0
  302. package/src/storage/schema/tables/TableUser.ts +16 -0
  303. package/src/storage/schema/tables/index.ts +16 -0
  304. package/src/storage/sync/StorageMySQLDojoReader.ts +696 -0
  305. package/src/storage/sync/index.ts +1 -0
  306. package/src/utility/Format.ts +133 -0
  307. package/src/utility/README.md +3 -0
  308. package/src/utility/ReaderUint8Array.ts +187 -0
  309. package/src/utility/ScriptTemplateBRC29.ts +73 -0
  310. package/src/utility/__tests/utilityHelpers.noBuffer.test.ts +109 -0
  311. package/src/utility/aggregateResults.ts +68 -0
  312. package/src/utility/identityUtils.ts +159 -0
  313. package/src/utility/index.all.ts +7 -0
  314. package/src/utility/index.client.ts +7 -0
  315. package/src/utility/parseTxScriptOffsets.ts +29 -0
  316. package/src/utility/stampLog.ts +69 -0
  317. package/src/utility/tscProofToMerklePath.ts +48 -0
  318. package/src/utility/utilityHelpers.buffer.ts +34 -0
  319. package/src/utility/utilityHelpers.noBuffer.ts +60 -0
  320. package/src/utility/utilityHelpers.ts +275 -0
  321. package/src/wab-client/WABClient.ts +94 -0
  322. package/src/wab-client/__tests/WABClient.man.test.ts +59 -0
  323. package/src/wab-client/auth-method-interactors/AuthMethodInteractor.ts +47 -0
  324. package/src/wab-client/auth-method-interactors/DevConsoleInteractor.ts +73 -0
  325. package/src/wab-client/auth-method-interactors/PersonaIDInteractor.ts +35 -0
  326. package/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.ts +72 -0
  327. package/syncVersions.js +71 -0
  328. package/test/Wallet/StorageClient/storageClient.man.test.ts +75 -0
  329. package/test/Wallet/action/abortAction.test.ts +47 -0
  330. package/test/Wallet/action/createAction.test.ts +299 -0
  331. package/test/Wallet/action/createAction2.test.ts +1273 -0
  332. package/test/Wallet/action/createActionToGenerateBeefs.man.test.ts +293 -0
  333. package/test/Wallet/action/internalizeAction.a.test.ts +286 -0
  334. package/test/Wallet/action/internalizeAction.test.ts +682 -0
  335. package/test/Wallet/action/relinquishOutput.test.ts +37 -0
  336. package/test/Wallet/certificate/acquireCertificate.test.ts +298 -0
  337. package/test/Wallet/certificate/listCertificates.test.ts +346 -0
  338. package/test/Wallet/construct/Wallet.constructor.test.ts +57 -0
  339. package/test/Wallet/get/getHeaderForHeight.test.ts +82 -0
  340. package/test/Wallet/get/getHeight.test.ts +52 -0
  341. package/test/Wallet/get/getKnownTxids.test.ts +86 -0
  342. package/test/Wallet/get/getNetwork.test.ts +27 -0
  343. package/test/Wallet/get/getVersion.test.ts +27 -0
  344. package/test/Wallet/list/listActions.test.ts +279 -0
  345. package/test/Wallet/list/listActions2.test.ts +1381 -0
  346. package/test/Wallet/list/listCertificates.test.ts +118 -0
  347. package/test/Wallet/list/listOutputs.test.ts +447 -0
  348. package/test/Wallet/live/walletLive.man.test.ts +521 -0
  349. package/test/Wallet/local/localWallet.man.test.ts +93 -0
  350. package/test/Wallet/local/localWallet2.man.test.ts +277 -0
  351. package/test/Wallet/signAction/mountaintop.man.test.ts +130 -0
  352. package/test/Wallet/specOps/specOps.man.test.ts +220 -0
  353. package/test/Wallet/support/janitor.man.test.ts +40 -0
  354. package/test/Wallet/support/operations.man.test.ts +407 -0
  355. package/test/Wallet/support/reqErrorReview.2025.05.06.man.test.ts +347 -0
  356. package/test/Wallet/sync/Wallet.sync.test.ts +215 -0
  357. package/test/Wallet/sync/Wallet.updateWalletLegacyTestData.man.test.ts +203 -0
  358. package/test/Wallet/sync/setActive.test.ts +170 -0
  359. package/test/WalletClient/LocalKVStore.man.test.ts +114 -0
  360. package/test/WalletClient/WERR.man.test.ts +35 -0
  361. package/test/bsv-ts-sdk/LocalKVStore.test.ts +102 -0
  362. package/test/checkDB.ts +57 -0
  363. package/test/checkdb +0 -0
  364. package/test/examples/backup.man.test.ts +59 -0
  365. package/test/examples/pushdrop.test.ts +282 -0
  366. package/test/monitor/Monitor.test.ts +620 -0
  367. package/test/services/Services.test.ts +263 -0
  368. package/test/storage/KnexMigrations.test.ts +86 -0
  369. package/test/storage/StorageMySQLDojoReader.man.test.ts +60 -0
  370. package/test/storage/count.test.ts +177 -0
  371. package/test/storage/find.test.ts +195 -0
  372. package/test/storage/findLegacy.test.ts +67 -0
  373. package/test/storage/idb/allocateChange.test.ts +251 -0
  374. package/test/storage/idb/count.test.ts +158 -0
  375. package/test/storage/idb/find.test.ts +177 -0
  376. package/test/storage/idb/idbSpeed.test.ts +36 -0
  377. package/test/storage/idb/insert.test.ts +268 -0
  378. package/test/storage/idb/transactionAbort.test.ts +108 -0
  379. package/test/storage/idb/update.test.ts +999 -0
  380. package/test/storage/insert.test.ts +278 -0
  381. package/test/storage/update.test.ts +1021 -0
  382. package/test/storage/update2.test.ts +897 -0
  383. package/test/utils/TestUtilsWalletStorage.ts +2526 -0
  384. package/test/utils/localWalletMethods.ts +363 -0
  385. package/test/utils/removeFailedFromDatabase.sql +17 -0
  386. package/ts2md.json +44 -0
  387. package/tsconfig.all.json +31 -0
  388. package/tsconfig.client.json +29 -0
  389. package/tsconfig.json +17 -0
  390. package/tsconfig.mobile.json +28 -0
@@ -0,0 +1,943 @@
1
+ import {
2
+ AbortActionArgs,
3
+ AbortActionResult,
4
+ Beef,
5
+ InternalizeActionArgs,
6
+ ListActionsResult,
7
+ ListCertificatesResult,
8
+ ListOutputsResult,
9
+ RelinquishCertificateArgs,
10
+ RelinquishOutputArgs,
11
+ Validation
12
+ } from '@bsv/sdk'
13
+ import { EntitySyncState } from '../storage/schema/entities'
14
+ import * as sdk from '../sdk'
15
+ import {
16
+ TableCertificate,
17
+ TableCertificateX,
18
+ TableOutput,
19
+ TableOutputBasket,
20
+ TableProvenTx,
21
+ TableProvenTxReq,
22
+ TableSettings,
23
+ TableUser
24
+ } from '../storage/schema/tables'
25
+ import { StorageProvider } from './StorageProvider'
26
+ import { StorageClient } from './remoting/StorageClient'
27
+
28
+ class ManagedStorage {
29
+ isAvailable: boolean
30
+ isStorageProvider: boolean
31
+ settings?: TableSettings
32
+ user?: TableUser
33
+
34
+ constructor(public storage: sdk.WalletStorageProvider) {
35
+ this.isStorageProvider = storage.isStorageProvider()
36
+ this.isAvailable = false
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The `WalletStorageManager` class delivers authentication checking storage access to the wallet.
42
+ *
43
+ * If manages multiple `StorageBase` derived storage services: one actice, the rest as backups.
44
+ *
45
+ * Of the storage services, one is 'active' at any one time.
46
+ * On startup, and whenever triggered by the wallet, `WalletStorageManager` runs a syncrhonization sequence:
47
+ *
48
+ * 1. While synchronizing, all other access to storage is blocked waiting.
49
+ * 2. The active service is confirmed, potentially triggering a resolution process if there is disagreement.
50
+ * 3. Changes are pushed from the active storage service to each inactive, backup service.
51
+ *
52
+ * Some storage services do not support multiple writers. `WalletStorageManager` manages wait-blocking write requests
53
+ * for these services.
54
+ */
55
+ export class WalletStorageManager implements sdk.WalletStorage {
56
+ /**
57
+ * All configured stores including current active, backups, and conflicting actives.
58
+ */
59
+ _stores: ManagedStorage[] = []
60
+ /**
61
+ * True if makeAvailable has been run and access to managed stores (active) is allowed
62
+ */
63
+ _isAvailable: boolean = false
64
+ /**
65
+ * The current active store which is only enabled if the store's user record activeStorage property matches its settings record storageIdentityKey property
66
+ */
67
+ _active?: ManagedStorage
68
+ /**
69
+ * Stores to which state is pushed by updateBackups.
70
+ */
71
+ _backups?: ManagedStorage[]
72
+ /**
73
+ * Stores whose user record activeStorage property disagrees with the active store's user record activeStorage property.
74
+ */
75
+ _conflictingActives?: ManagedStorage[]
76
+ /**
77
+ * identityKey is always valid, userId and isActive are valid only if _isAvailable
78
+ */
79
+ _authId: sdk.AuthId
80
+ /**
81
+ * Configured services if any. If valid, shared with stores (which may ignore it).
82
+ */
83
+ _services?: sdk.WalletServices
84
+
85
+ /**
86
+ * Creates a new WalletStorageManager with the given identityKey and optional active and backup storage providers.
87
+ *
88
+ * @param identityKey The identity key of the user for whom this wallet is being managed.
89
+ * @param active An optional active storage provider. If not provided, no active storage will be set.
90
+ * @param backups An optional array of backup storage providers. If not provided, no backups will be set.
91
+ */
92
+ constructor(identityKey: string, active?: sdk.WalletStorageProvider, backups?: sdk.WalletStorageProvider[]) {
93
+ const stores = [...(backups || [])]
94
+ if (active) stores.unshift(active)
95
+ this._stores = stores.map(s => new ManagedStorage(s))
96
+ this._authId = { identityKey }
97
+ }
98
+
99
+ isStorageProvider(): boolean {
100
+ return false
101
+ }
102
+
103
+ isAvailable(): boolean {
104
+ return this._isAvailable
105
+ }
106
+
107
+ /**
108
+ * The active storage is "enabled" only if its `storageIdentityKey` matches the user's currently selected `activeStorage`,
109
+ * and only if there are no stores with conflicting `activeStorage` selections.
110
+ *
111
+ * A wallet may be created without including the user's currently selected active storage. This allows readonly access to their wallet data.
112
+ *
113
+ * In addition, if there are conflicting `activeStorage` selections among backup storage providers then the active remains disabled.
114
+ */
115
+ get isActiveEnabled(): boolean {
116
+ return (
117
+ this._active !== undefined &&
118
+ this._active.settings!.storageIdentityKey === this._active.user!.activeStorage &&
119
+ this._conflictingActives !== undefined &&
120
+ this._conflictingActives.length === 0
121
+ )
122
+ }
123
+
124
+ /**
125
+ * @returns true if at least one WalletStorageProvider has been added.
126
+ */
127
+ canMakeAvailable(): boolean {
128
+ return this._stores.length > 0
129
+ }
130
+
131
+ /**
132
+ * This async function must be called after construction and before
133
+ * any other async function can proceed.
134
+ *
135
+ * Runs through `_stores` validating all properties and partitioning across `_active`, `_backups`, `_conflictingActives`.
136
+ *
137
+ * @throws WERR_INVALID_PARAMETER if canMakeAvailable returns false.
138
+ *
139
+ * @returns {TableSettings} from the active storage.
140
+ */
141
+ async makeAvailable(): Promise<TableSettings> {
142
+ if (this._isAvailable) return this._active!.settings!
143
+
144
+ this._active = undefined
145
+ this._backups = []
146
+ this._conflictingActives = []
147
+
148
+ if (this._stores.length < 1)
149
+ throw new sdk.WERR_INVALID_PARAMETER('active', 'valid. Must add active storage provider to wallet.')
150
+
151
+ // Initial backups. conflictingActives will be removed.
152
+ const backups: ManagedStorage[] = []
153
+ let i = -1
154
+ for (const store of this._stores) {
155
+ i++
156
+ if (!store.isAvailable || !store.settings || !store.user) {
157
+ // Validate all ManagedStorage properties.
158
+ store.settings = await store.storage.makeAvailable()
159
+ const r = await store.storage.findOrInsertUser(this._authId.identityKey)
160
+ store.user = r.user
161
+ store.isAvailable = true
162
+ }
163
+ if (!this._active)
164
+ // _stores[0] becomes the default active store. It may be replaced if it is not the user's "enabled" activeStorage and that store is found among the remainder (backups).
165
+ this._active = store
166
+ else {
167
+ const ua = store.user!.activeStorage
168
+ const si = store.settings!.storageIdentityKey
169
+ if (ua === si && !this.isActiveEnabled) {
170
+ // This store's user record selects it as an enabled active storage...
171
+ // swap the current not-enabled active for this storeage.
172
+ backups.push(this._active!)
173
+ this._active = store
174
+ } else {
175
+ // This store is a backup: Its user record selects some other storage as active.
176
+ backups.push(store)
177
+ }
178
+ }
179
+ }
180
+
181
+ // Review backups, partition out conflicting actives.
182
+ const si = this._active!.settings?.storageIdentityKey
183
+ for (const store of backups) {
184
+ if (store.user!.activeStorage !== si) this._conflictingActives.push(store)
185
+ else this._backups.push(store)
186
+ }
187
+
188
+ this._isAvailable = true
189
+ this._authId.userId = this._active!.user!.userId
190
+ this._authId.isActive = this.isActiveEnabled
191
+
192
+ return this._active!.settings!
193
+ }
194
+
195
+ private verifyActive(): ManagedStorage {
196
+ if (!this._active || !this._isAvailable)
197
+ throw new sdk.WERR_INVALID_OPERATION(
198
+ 'An active WalletStorageProvider must be added to this WalletStorageManager and makeAvailable must be called.'
199
+ )
200
+ return this._active
201
+ }
202
+
203
+ async getAuth(mustBeActive?: boolean): Promise<sdk.AuthId> {
204
+ if (!this.isAvailable()) await this.makeAvailable()
205
+ if (mustBeActive && !this._authId.isActive) throw new sdk.WERR_NOT_ACTIVE()
206
+ return this._authId
207
+ }
208
+
209
+ async getUserId(): Promise<number> {
210
+ return (await this.getAuth()).userId!
211
+ }
212
+
213
+ getActive(): sdk.WalletStorageProvider {
214
+ return this.verifyActive().storage
215
+ }
216
+
217
+ getActiveSettings(): TableSettings {
218
+ return this.verifyActive().settings!
219
+ }
220
+
221
+ getActiveUser(): TableUser {
222
+ return this.verifyActive().user!
223
+ }
224
+
225
+ getActiveStore(): string {
226
+ return this.verifyActive().settings!.storageIdentityKey
227
+ }
228
+
229
+ getActiveStoreName(): string {
230
+ return this.verifyActive().settings!.storageName
231
+ }
232
+
233
+ getBackupStores(): string[] {
234
+ this.verifyActive()
235
+ return this._backups!.map(b => b.settings!.storageIdentityKey)
236
+ }
237
+
238
+ getConflictingStores(): string[] {
239
+ this.verifyActive()
240
+ return this._conflictingActives!.map(b => b.settings!.storageIdentityKey)
241
+ }
242
+
243
+ getAllStores(): string[] {
244
+ this.verifyActive()
245
+ return this._stores.map(b => b.settings!.storageIdentityKey)
246
+ }
247
+
248
+ private readonly readerLocks: Array<(value: void | PromiseLike<void>) => void> = []
249
+ private readonly writerLocks: Array<(value: void | PromiseLike<void>) => void> = []
250
+ private readonly syncLocks: Array<(value: void | PromiseLike<void>) => void> = []
251
+ private readonly spLocks: Array<(value: void | PromiseLike<void>) => void> = []
252
+
253
+ private async getActiveLock(lockQueue: Array<(value: void | PromiseLike<void>) => void>): Promise<void> {
254
+ if (!this.isAvailable()) await this.makeAvailable()
255
+
256
+ let resolveNewLock: () => void = () => {}
257
+ const newLock = new Promise<void>(resolve => {
258
+ resolveNewLock = resolve
259
+ lockQueue.push(resolve)
260
+ })
261
+ if (lockQueue.length === 1) {
262
+ resolveNewLock()
263
+ }
264
+ await newLock
265
+ }
266
+
267
+ private releaseActiveLock(queue: Array<(value: void | PromiseLike<void>) => void>): void {
268
+ queue.shift() // Remove the current lock from the queue
269
+ if (queue.length > 0) {
270
+ queue[0]()
271
+ }
272
+ }
273
+
274
+ private async getActiveForReader(): Promise<sdk.WalletStorageReader> {
275
+ await this.getActiveLock(this.readerLocks)
276
+ return this.getActive()
277
+ }
278
+ private releaseActiveForReader(): void {
279
+ this.releaseActiveLock(this.readerLocks)
280
+ }
281
+
282
+ private async getActiveForWriter(): Promise<sdk.WalletStorageWriter> {
283
+ await this.getActiveLock(this.readerLocks)
284
+ await this.getActiveLock(this.writerLocks)
285
+ return this.getActive()
286
+ }
287
+ private releaseActiveForWriter(): void {
288
+ this.releaseActiveLock(this.writerLocks)
289
+ this.releaseActiveLock(this.readerLocks)
290
+ }
291
+
292
+ private async getActiveForSync(): Promise<sdk.WalletStorageSync> {
293
+ await this.getActiveLock(this.readerLocks)
294
+ await this.getActiveLock(this.writerLocks)
295
+ await this.getActiveLock(this.syncLocks)
296
+ return this.getActive()
297
+ }
298
+ private releaseActiveForSync(): void {
299
+ this.releaseActiveLock(this.syncLocks)
300
+ this.releaseActiveLock(this.writerLocks)
301
+ this.releaseActiveLock(this.readerLocks)
302
+ }
303
+
304
+ private async getActiveForStorageProvider(): Promise<StorageProvider> {
305
+ await this.getActiveLock(this.readerLocks)
306
+ await this.getActiveLock(this.writerLocks)
307
+ await this.getActiveLock(this.syncLocks)
308
+ await this.getActiveLock(this.spLocks)
309
+
310
+ const active = this.getActive()
311
+ // We can finally confirm that active storage is still able to support `StorageProvider`
312
+ if (!active.isStorageProvider())
313
+ throw new sdk.WERR_INVALID_OPERATION(
314
+ 'Active "WalletStorageProvider" does not support "StorageProvider" interface.'
315
+ )
316
+ // Allow the sync to proceed on the active store.
317
+ return active as unknown as StorageProvider
318
+ }
319
+ private releaseActiveForStorageProvider(): void {
320
+ this.releaseActiveLock(this.spLocks)
321
+ this.releaseActiveLock(this.syncLocks)
322
+ this.releaseActiveLock(this.writerLocks)
323
+ this.releaseActiveLock(this.readerLocks)
324
+ }
325
+
326
+ async runAsWriter<R>(writer: (active: sdk.WalletStorageWriter) => Promise<R>): Promise<R> {
327
+ try {
328
+ const active = await this.getActiveForWriter()
329
+ const r = await writer(active)
330
+ return r
331
+ } finally {
332
+ this.releaseActiveForWriter()
333
+ }
334
+ }
335
+
336
+ async runAsReader<R>(reader: (active: sdk.WalletStorageReader) => Promise<R>): Promise<R> {
337
+ try {
338
+ const active = await this.getActiveForReader()
339
+ const r = await reader(active)
340
+ return r
341
+ } finally {
342
+ this.releaseActiveForReader()
343
+ }
344
+ }
345
+
346
+ /**
347
+ *
348
+ * @param sync the function to run with sync access lock
349
+ * @param activeSync from chained sync functions, active storage already held under sync access lock.
350
+ * @returns
351
+ */
352
+ async runAsSync<R>(
353
+ sync: (active: sdk.WalletStorageSync) => Promise<R>,
354
+ activeSync?: sdk.WalletStorageSync
355
+ ): Promise<R> {
356
+ try {
357
+ const active = activeSync || (await this.getActiveForSync())
358
+ const r = await sync(active)
359
+ return r
360
+ } finally {
361
+ if (!activeSync) this.releaseActiveForSync()
362
+ }
363
+ }
364
+
365
+ async runAsStorageProvider<R>(sync: (active: StorageProvider) => Promise<R>): Promise<R> {
366
+ try {
367
+ const active = await this.getActiveForStorageProvider()
368
+ const r = await sync(active)
369
+ return r
370
+ } finally {
371
+ this.releaseActiveForStorageProvider()
372
+ }
373
+ }
374
+
375
+ /**
376
+ *
377
+ * @returns true if the active `WalletStorageProvider` also implements `StorageProvider`
378
+ */
379
+ isActiveStorageProvider(): boolean {
380
+ return this.getActive().isStorageProvider()
381
+ }
382
+
383
+ async addWalletStorageProvider(provider: sdk.WalletStorageProvider): Promise<void> {
384
+ await provider.makeAvailable()
385
+ if (this._services) provider.setServices(this._services)
386
+ this._stores.push(new ManagedStorage(provider))
387
+ this._isAvailable = false
388
+ await this.makeAvailable()
389
+ }
390
+
391
+ setServices(v: sdk.WalletServices) {
392
+ this._services = v
393
+ for (const store of this._stores) store.storage.setServices(v)
394
+ }
395
+ getServices(): sdk.WalletServices {
396
+ if (!this._services) throw new sdk.WERR_INVALID_OPERATION('Must setServices first.')
397
+ return this._services
398
+ }
399
+
400
+ getSettings(): TableSettings {
401
+ return this.getActive().getSettings()
402
+ }
403
+
404
+ async migrate(storageName: string, storageIdentityKey: string): Promise<string> {
405
+ return await this.runAsWriter(async writer => {
406
+ return writer.migrate(storageName, storageIdentityKey)
407
+ })
408
+ }
409
+
410
+ async destroy(): Promise<void> {
411
+ if (this._stores.length < 1) return
412
+ return await this.runAsWriter(async writer => {
413
+ for (const store of this._stores) await store.storage.destroy()
414
+ })
415
+ }
416
+
417
+ async findOrInsertUser(identityKey: string): Promise<{ user: TableUser; isNew: boolean }> {
418
+ const auth = await this.getAuth()
419
+ if (identityKey != auth.identityKey) throw new sdk.WERR_UNAUTHORIZED()
420
+
421
+ return await this.runAsWriter(async writer => {
422
+ const r = await writer.findOrInsertUser(identityKey)
423
+
424
+ if (auth.userId && auth.userId !== r.user.userId)
425
+ throw new sdk.WERR_INTERNAL('userId may not change for given identityKey')
426
+ this._authId.userId = r.user.userId
427
+ return r
428
+ })
429
+ }
430
+
431
+ async abortAction(args: AbortActionArgs): Promise<AbortActionResult> {
432
+ Validation.validateAbortActionArgs(args)
433
+ return await this.runAsWriter(async writer => {
434
+ const auth = await this.getAuth(true)
435
+ return await writer.abortAction(auth, args)
436
+ })
437
+ }
438
+ async createAction(vargs: Validation.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult> {
439
+ return await this.runAsWriter(async writer => {
440
+ const auth = await this.getAuth(true)
441
+ return await writer.createAction(auth, vargs)
442
+ })
443
+ }
444
+ async internalizeAction(args: InternalizeActionArgs): Promise<sdk.StorageInternalizeActionResult> {
445
+ Validation.validateInternalizeActionArgs(args)
446
+ return await this.runAsWriter(async writer => {
447
+ const auth = await this.getAuth(true)
448
+ return await writer.internalizeAction(auth, args)
449
+ })
450
+ }
451
+
452
+ async relinquishCertificate(args: RelinquishCertificateArgs): Promise<number> {
453
+ Validation.validateRelinquishCertificateArgs(args)
454
+ return await this.runAsWriter(async writer => {
455
+ const auth = await this.getAuth(true)
456
+ return await writer.relinquishCertificate(auth, args)
457
+ })
458
+ }
459
+ async relinquishOutput(args: RelinquishOutputArgs): Promise<number> {
460
+ Validation.validateRelinquishOutputArgs(args)
461
+ return await this.runAsWriter(async writer => {
462
+ const auth = await this.getAuth(true)
463
+ return await writer.relinquishOutput(auth, args)
464
+ })
465
+ }
466
+
467
+ async processAction(args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults> {
468
+ return await this.runAsWriter(async writer => {
469
+ const auth = await this.getAuth(true)
470
+ return await writer.processAction(auth, args)
471
+ })
472
+ }
473
+ async insertCertificate(certificate: TableCertificate): Promise<number> {
474
+ return await this.runAsWriter(async writer => {
475
+ const auth = await this.getAuth(true)
476
+ return await writer.insertCertificateAuth(auth, certificate)
477
+ })
478
+ }
479
+
480
+ async listActions(vargs: Validation.ValidListActionsArgs): Promise<ListActionsResult> {
481
+ const auth = await this.getAuth()
482
+ return await this.runAsReader(async reader => {
483
+ return await reader.listActions(auth, vargs)
484
+ })
485
+ }
486
+ async listCertificates(args: Validation.ValidListCertificatesArgs): Promise<ListCertificatesResult> {
487
+ const auth = await this.getAuth()
488
+ return await this.runAsReader(async reader => {
489
+ return await reader.listCertificates(auth, args)
490
+ })
491
+ }
492
+ async listOutputs(vargs: Validation.ValidListOutputsArgs): Promise<ListOutputsResult> {
493
+ const auth = await this.getAuth()
494
+ return await this.runAsReader(async reader => {
495
+ return await reader.listOutputs(auth, vargs)
496
+ })
497
+ }
498
+ async findCertificates(args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]> {
499
+ const auth = await this.getAuth()
500
+ return await this.runAsReader(async reader => {
501
+ return await reader.findCertificatesAuth(auth, args)
502
+ })
503
+ }
504
+ async findOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]> {
505
+ const auth = await this.getAuth()
506
+ return await this.runAsReader(async reader => {
507
+ return await reader.findOutputBasketsAuth(auth, args)
508
+ })
509
+ }
510
+ async findOutputs(args: sdk.FindOutputsArgs): Promise<TableOutput[]> {
511
+ const auth = await this.getAuth()
512
+ return await this.runAsReader(async reader => {
513
+ return await reader.findOutputsAuth(auth, args)
514
+ })
515
+ }
516
+
517
+ async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]> {
518
+ return await this.runAsReader(async reader => {
519
+ return await reader.findProvenTxReqs(args)
520
+ })
521
+ }
522
+
523
+ /**
524
+ * For each proven_txs record currently sourcing its transaction merkle proof from the given deactivated header,
525
+ * attempt to reprove the transaction against the current chain,
526
+ * updating the proven_txs record if a new valid proof is found.
527
+ *
528
+ * @param deactivatedHash An orphaned header than may have served as a proof source for proven_txs records.
529
+ * @returns
530
+ */
531
+ async reproveHeader(deactivatedHash: string): Promise<sdk.ReproveHeaderResult> {
532
+ const r: sdk.ReproveHeaderResult = { log: '', updated: [], unchanged: [], unavailable: [] }
533
+ const services = this.getServices()
534
+ const chaintracker = await services.getChainTracker()
535
+
536
+ // Lookup all the proven_txs records matching the deactivated headers
537
+ let ptxs: TableProvenTx[] = []
538
+ await this.runAsStorageProvider(async sp => {
539
+ ptxs = await sp.findProvenTxs({ partial: { blockHash: deactivatedHash } })
540
+ })
541
+
542
+ r.log += ` block ${deactivatedHash} orphaned with ${ptxs.length} impacted transactions\n`
543
+
544
+ for (const ptx of ptxs) {
545
+ // Loop over proven_txs records matching the deactivated header
546
+ const rp = await this.reproveProven(ptx, true)
547
+
548
+ r.log += rp.log
549
+ if (rp.unavailable) r.unavailable.push(ptx)
550
+ if (rp.unchanged) r.unchanged.push(ptx)
551
+ if (rp.updated) r.updated.push({ was: ptx, update: rp.updated.update, logUpdate: rp.updated.logUpdate })
552
+ }
553
+
554
+ if (r.updated.length > 0) {
555
+ await this.runAsStorageProvider(async sp => {
556
+ for (const u of r.updated) {
557
+ await sp.updateProvenTx(u.was.provenTxId, u.update)
558
+ r.log += ` txid ${u.was.txid} proof data updated\n` + u.logUpdate
559
+ }
560
+ })
561
+ }
562
+
563
+ return r
564
+ }
565
+
566
+ /**
567
+ * Extends the Beef `verify` function to handle BUMPs that have become invalid due to a chain reorg,
568
+ * and originated from proven_txs records tracked by this storage.
569
+ *
570
+ * This method is optimized for making sure outgoing beefs are valid before sharing them externally.
571
+ * In particular, it only "repairs" proofs previously tracked by this storage.
572
+ *
573
+ * Any merkle root that fails `isValidRootForHeight` triggers a reprove attempt for that block header.
574
+ * This results in proven_txs with invalid proofs being updated with new valid proofs where possible.
575
+ *
576
+ * @param beef
577
+ * @param allowTxidOnly
578
+ * @returns VerifyAndRepairBeefResult, in particular `verifiedBeef` is valid only verify and repair succeeded fully.
579
+ */
580
+ async verifyAndRepairBeef(beef: Beef, allowTxidOnly?: boolean): Promise<VerifyAndRepairBeefResult> {
581
+ throw new sdk.WERR_NOT_IMPLEMENTED()
582
+
583
+ const r: VerifyAndRepairBeefResult = {
584
+ isStructurallyValid: false,
585
+ originalRoots: {},
586
+ invalidRoots: {}
587
+ }
588
+ const services = this.getServices()
589
+ const chaintracker = await services.getChainTracker()
590
+
591
+ ;({ valid: r.isStructurallyValid, roots: r.originalRoots } = beef.verifyValid(allowTxidOnly))
592
+
593
+ if (!r.isStructurallyValid) return r
594
+
595
+ for (const [heightStr, root] of Object.entries(r.originalRoots)) {
596
+ const height = Number(heightStr)
597
+ const isValid = await chaintracker.isValidRootForHeight(root, height)
598
+ if (!isValid) {
599
+ // root is not currently the valid hash for this height according to the chaintracker.
600
+ // What beef txids depended on this root:
601
+ const txids = beef.txs
602
+ .filter(tx => tx.bumpIndex !== undefined && beef.bumps[tx.bumpIndex].blockHeight === height)
603
+ .map(tx => tx.txid)
604
+ const reproveResults = await this.reproveHeader(root)
605
+ r.invalidRoots[height] = { root, reproveResults }
606
+ }
607
+ }
608
+
609
+ if (Object.keys(r.invalidRoots).length === 0) {
610
+ // There are no invalid merkle roots and the beef is structurally valid.
611
+ // The beef is fully verified.
612
+ return r
613
+ }
614
+
615
+ // beef is structurally valid but has invalid merkle roots.
616
+ // Attempt to repair the invalid roots by reproving all txids in this beef that relied on them.
617
+
618
+ // All invalid BUMPs must be removed from the beef
619
+ // and all txid's that were proven by those BUMPs need
620
+ // new beefs merged into the beef.
621
+ // In most cases, this will be a replacement BUMP,
622
+ // but it may also require a deeper proof.
623
+
624
+ return r
625
+ }
626
+
627
+ /**
628
+ * Attempt to reprove the transaction against the current chain,
629
+ * If a new valid proof is found and noUpdate is not true,
630
+ * update the proven_txs record with new block and merkle proof data.
631
+ * If noUpdate is true, the update to be applied is available in the returned result.
632
+ *
633
+ * @param ptx proven_txs record to reprove
634
+ * @param noUpdate
635
+ * @returns
636
+ */
637
+ async reproveProven(ptx: TableProvenTx, noUpdate?: boolean): Promise<sdk.ReproveProvenResult> {
638
+ const r: sdk.ReproveProvenResult = { log: '', updated: undefined, unchanged: false, unavailable: false }
639
+ const services = this.getServices()
640
+ const chaintracker = await services.getChainTracker()
641
+
642
+ const mpr = await services.getMerklePath(ptx.txid)
643
+ if (mpr.merklePath && mpr.header) {
644
+ const mp = mpr.merklePath
645
+ const h = mpr.header
646
+ const leaf = mp.path[0].find(leaf => leaf.txid === true && leaf.hash === ptx.txid)
647
+ if (leaf) {
648
+ const update: Partial<TableProvenTx> = {
649
+ height: mp.blockHeight,
650
+ index: leaf.offset,
651
+ merklePath: mp.toBinary(),
652
+ merkleRoot: h.merkleRoot,
653
+ blockHash: h.hash
654
+ }
655
+ if (update.blockHash === ptx.blockHash) {
656
+ r.log += ` txid ${ptx.txid} merkle path update still based on deactivated header ${ptx.blockHash}\n`
657
+ r.unchanged = true
658
+ } else {
659
+ // Verify the new proof's validity.
660
+ const merkleRoot = mp.computeRoot(ptx.txid)
661
+ const isValid = await chaintracker.isValidRootForHeight(merkleRoot, update.height!)
662
+ const logUpdate = ` height ${ptx.height} ${ptx.height === update.height ? 'unchanged' : `-> ${update.height}`}\n`
663
+ r.log += ` blockHash ${ptx.blockHash} -> ${update.blockHash}\n`
664
+ r.log += ` merkleRoot ${ptx.merkleRoot} -> ${update.merkleRoot}\n`
665
+ r.log += ` index ${ptx.index} -> ${update.index}\n`
666
+ if (isValid) {
667
+ r.updated = { update, logUpdate }
668
+ } else {
669
+ r.log +=
670
+ ` txid ${ptx.txid} chaintracker fails to confirm updated merkle path update invalid\n` + logUpdate
671
+ r.unavailable = true
672
+ }
673
+ }
674
+ } else {
675
+ r.log += ` txid ${ptx.txid} merkle path update doesn't include txid\n`
676
+ r.unavailable = true
677
+ }
678
+ } else {
679
+ r.log += ` txid ${ptx.txid} merkle path update unavailable\n`
680
+ r.unavailable = true
681
+ }
682
+
683
+ if (r.updated && !noUpdate) {
684
+ await this.runAsStorageProvider(async sp => {
685
+ await sp.updateProvenTx(ptx.provenTxId, r.updated!.update)
686
+ r.log += ` txid ${ptx.txid} proof data updated\n` + r.updated!.logUpdate
687
+ })
688
+ }
689
+
690
+ return r
691
+ }
692
+
693
+ async syncFromReader(
694
+ identityKey: string,
695
+ reader: sdk.WalletStorageSyncReader,
696
+ activeSync?: sdk.WalletStorageSync,
697
+ log: string = ''
698
+ ): Promise<{ inserts: number; updates: number; log: string }> {
699
+ const auth = await this.getAuth()
700
+ if (identityKey !== auth.identityKey) throw new sdk.WERR_UNAUTHORIZED()
701
+
702
+ const readerSettings = await reader.makeAvailable()
703
+
704
+ let inserts = 0,
705
+ updates = 0
706
+
707
+ log = await this.runAsSync(async sync => {
708
+ const writer = sync
709
+ const writerSettings = this.getSettings()
710
+
711
+ log += `syncFromReader from ${readerSettings.storageName} to ${writerSettings.storageName}\n`
712
+
713
+ let i = -1
714
+ for (;;) {
715
+ i++
716
+ const ss = await EntitySyncState.fromStorage(writer, identityKey, readerSettings)
717
+ const args = ss.makeRequestSyncChunkArgs(identityKey, writerSettings.storageIdentityKey)
718
+ const chunk = await reader.getSyncChunk(args)
719
+ if (chunk.user) {
720
+ // Merging state from a reader cannot update activeStorage
721
+ chunk.user.activeStorage = this._active!.user!.activeStorage
722
+ }
723
+ const r = await writer.processSyncChunk(args, chunk)
724
+ inserts += r.inserts
725
+ updates += r.updates
726
+ log += `chunk ${i} inserted ${r.inserts} updated ${r.updates} ${r.maxUpdated_at}\n`
727
+ if (r.done) break
728
+ }
729
+ log += `syncFromReader complete: ${inserts} inserts, ${updates} updates\n`
730
+ return log
731
+ }, activeSync)
732
+
733
+ return { inserts, updates, log }
734
+ }
735
+
736
+ async syncToWriter(
737
+ auth: sdk.AuthId,
738
+ writer: sdk.WalletStorageProvider,
739
+ activeSync?: sdk.WalletStorageSync,
740
+ log: string = '',
741
+ progLog?: (s: string) => string
742
+ ): Promise<{ inserts: number; updates: number; log: string }> {
743
+ progLog ||= s => s
744
+ const identityKey = auth.identityKey
745
+
746
+ const writerSettings = await writer.makeAvailable()
747
+
748
+ let inserts = 0,
749
+ updates = 0
750
+
751
+ log = await this.runAsSync(async sync => {
752
+ const reader = sync
753
+ const readerSettings = reader.getSettings()
754
+
755
+ log += progLog(`syncToWriter from ${readerSettings.storageName} to ${writerSettings.storageName}\n`)
756
+
757
+ let i = -1
758
+ for (;;) {
759
+ i++
760
+ const ss = await EntitySyncState.fromStorage(writer, identityKey, readerSettings)
761
+ const args = ss.makeRequestSyncChunkArgs(identityKey, writerSettings.storageIdentityKey)
762
+ const chunk = await reader.getSyncChunk(args)
763
+ log += EntitySyncState.syncChunkSummary(chunk)
764
+ const r = await writer.processSyncChunk(args, chunk)
765
+ inserts += r.inserts
766
+ updates += r.updates
767
+ log += progLog(`chunk ${i} inserted ${r.inserts} updated ${r.updates} ${r.maxUpdated_at}\n`)
768
+ if (r.done) break
769
+ }
770
+ log += progLog(`syncToWriter complete: ${inserts} inserts, ${updates} updates\n`)
771
+ return log
772
+ }, activeSync)
773
+
774
+ return { inserts, updates, log }
775
+ }
776
+
777
+ async updateBackups(activeSync?: sdk.WalletStorageSync, progLog?: (s: string) => string): Promise<string> {
778
+ progLog ||= s => s
779
+ const auth = await this.getAuth(true)
780
+ return await this.runAsSync(async sync => {
781
+ let log = progLog(`BACKUP CURRENT ACTIVE TO ${this._backups!.length} STORES\n`)
782
+ for (const backup of this._backups!) {
783
+ const stwr = await this.syncToWriter(auth, backup.storage, sync, undefined, progLog)
784
+ log += stwr.log
785
+ }
786
+ return log
787
+ }, activeSync)
788
+ }
789
+
790
+ /**
791
+ * Updates backups and switches to new active storage provider from among current backup providers.
792
+ *
793
+ * Also resolves conflicting actives.
794
+ *
795
+ * @param storageIdentityKey of current backup storage provider that is to become the new active provider.
796
+ */
797
+ async setActive(storageIdentityKey: string, progLog?: (s: string) => string): Promise<string> {
798
+ progLog ||= s => s
799
+ if (!this.isAvailable()) await this.makeAvailable()
800
+
801
+ // Confirm a valid storageIdentityKey: must match one of the _stores.
802
+ const newActiveIndex = this._stores.findIndex(s => s.settings!.storageIdentityKey === storageIdentityKey)
803
+ if (newActiveIndex < 0)
804
+ throw new sdk.WERR_INVALID_PARAMETER(
805
+ 'storageIdentityKey',
806
+ `registered with this "WalletStorageManager". ${storageIdentityKey} does not match any managed store.`
807
+ )
808
+
809
+ const identityKey = (await this.getAuth()).identityKey
810
+ const newActive = this._stores[newActiveIndex]
811
+
812
+ let log = progLog(`setActive to ${newActive.settings!.storageName}`)
813
+
814
+ if (storageIdentityKey === this.getActiveStore() && this.isActiveEnabled)
815
+ /** Setting the current active as the new active is a permitted no-op. */
816
+ return log + progLog(` unchanged\n`)
817
+
818
+ log += progLog('\n')
819
+
820
+ log += await this.runAsSync(async sync => {
821
+ let log = ''
822
+
823
+ if (this._conflictingActives!.length > 0) {
824
+ // Merge state from conflicting actives into `newActive`.
825
+
826
+ // Handle case where new active is current active to resolve conflicts.
827
+ // And where new active is one of the current conflict actives.
828
+ this._conflictingActives!.push(this._active!)
829
+ // Remove the new active from conflicting actives and
830
+ // set new active as the conflicting active that matches the target `storageIdentityKey`
831
+ this._conflictingActives = this._conflictingActives!.filter(ca => {
832
+ const isNewActive = ca.settings!.storageIdentityKey === storageIdentityKey
833
+ return !isNewActive
834
+ })
835
+
836
+ // Merge state from conflicting actives into `newActive`.
837
+ for (const conflict of this._conflictingActives) {
838
+ log += progLog('MERGING STATE FROM CONFLICTING ACTIVES:\n')
839
+ const sfr = await this.syncToWriter(
840
+ { identityKey, userId: newActive.user!.userId, isActive: false },
841
+ newActive.storage,
842
+ conflict.storage,
843
+ undefined,
844
+ progLog
845
+ )
846
+ log += sfr.log
847
+ }
848
+ log += progLog('PROPAGATE MERGED ACTIVE STATE TO NON-ACTIVES\n')
849
+ } else {
850
+ log += progLog('BACKUP CURRENT ACTIVE STATE THEN SET NEW ACTIVE\n')
851
+ }
852
+
853
+ // If there were conflicting actives,
854
+ // Push state merged from all merged actives into newActive to all stores other than the now single active.
855
+ // Otherwise,
856
+ // Push state from current active to all other stores.
857
+ const backupSource = this._conflictingActives!.length > 0 ? newActive : this._active!
858
+
859
+ // Update the backupSource's user record with the new activeStorage
860
+ // which will propagate to all other stores in the following backup loop.
861
+ await backupSource.storage.setActive({ identityKey, userId: backupSource.user!.userId }, storageIdentityKey)
862
+
863
+ for (const store of this._stores) {
864
+ // Update cached user.activeStorage of all stores
865
+ store.user!.activeStorage = storageIdentityKey
866
+
867
+ if (store.settings!.storageIdentityKey !== backupSource.settings!.storageIdentityKey) {
868
+ // If this store is not the backupSource store push state from backupSource to this store.
869
+ const stwr = await this.syncToWriter(
870
+ { identityKey, userId: store.user!.userId, isActive: false },
871
+ store.storage,
872
+ backupSource.storage,
873
+ undefined,
874
+ progLog
875
+ )
876
+ log += stwr.log
877
+ }
878
+ }
879
+
880
+ this._isAvailable = false
881
+ await this.makeAvailable()
882
+
883
+ return log
884
+ })
885
+
886
+ return log
887
+ }
888
+
889
+ getStoreEndpointURL(store: ManagedStorage): string | undefined {
890
+ if (store.storage.constructor.name === 'StorageClient') return (store.storage as StorageClient).endpointUrl
891
+ return undefined
892
+ }
893
+
894
+ getStores(): sdk.WalletStorageInfo[] {
895
+ const stores: sdk.WalletStorageInfo[] = []
896
+ if (this._active) {
897
+ stores.push({
898
+ isActive: true,
899
+ isEnabled: this.isActiveEnabled,
900
+ isBackup: false,
901
+ isConflicting: false,
902
+ userId: this._active.user!.userId,
903
+ storageIdentityKey: this._active.settings!.storageIdentityKey,
904
+ storageName: this._active.settings!.storageName,
905
+ storageClass: this._active.storage.constructor.name,
906
+ endpointURL: this.getStoreEndpointURL(this._active)
907
+ })
908
+ }
909
+ for (const store of this._conflictingActives || []) {
910
+ stores.push({
911
+ isActive: true,
912
+ isEnabled: false,
913
+ isBackup: false,
914
+ isConflicting: true,
915
+ userId: store.user!.userId,
916
+ storageIdentityKey: store.settings!.storageIdentityKey,
917
+ storageName: store.settings!.storageName,
918
+ storageClass: store.storage.constructor.name,
919
+ endpointURL: this.getStoreEndpointURL(store)
920
+ })
921
+ }
922
+ for (const store of this._backups || []) {
923
+ stores.push({
924
+ isActive: false,
925
+ isEnabled: false,
926
+ isBackup: true,
927
+ isConflicting: false,
928
+ userId: store.user!.userId,
929
+ storageIdentityKey: store.settings!.storageIdentityKey,
930
+ storageName: store.settings!.storageName,
931
+ storageClass: store.storage.constructor.name,
932
+ endpointURL: this.getStoreEndpointURL(store)
933
+ })
934
+ }
935
+ return stores
936
+ }
937
+ }
938
+
939
+ export interface VerifyAndRepairBeefResult {
940
+ isStructurallyValid: boolean
941
+ originalRoots: Record<number, string>
942
+ invalidRoots: Record<number, { root: string; reproveResults: sdk.ReproveHeaderResult }>
943
+ }