@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.
- package/.claude/settings.local.json +10 -0
- package/.env.template +22 -0
- package/.github/ISSUE_TEMPLATE/bug_report.md +40 -0
- package/.github/ISSUE_TEMPLATE/discussion.md +24 -0
- package/.github/pull_request_template.md +22 -0
- package/.github/workflows/push.yaml +145 -0
- package/.prettierrc +10 -0
- package/CHANGELOG.md +280 -0
- package/CONTRIBUTING.md +89 -0
- package/README.md +43 -0
- package/docs/README.md +85 -0
- package/docs/client.md +19627 -0
- package/docs/monitor.md +953 -0
- package/docs/open-rpc/index.html +46 -0
- package/docs/services.md +6377 -0
- package/docs/setup.md +1268 -0
- package/docs/storage.md +5367 -0
- package/docs/wallet.md +19626 -0
- package/jest.config.ts +25 -0
- package/license.md +28 -0
- package/out/tsconfig.all.tsbuildinfo +1 -0
- package/package.json +63 -0
- package/src/CWIStyleWalletManager.ts +1999 -0
- package/src/Setup.ts +579 -0
- package/src/SetupClient.ts +322 -0
- package/src/SetupWallet.ts +108 -0
- package/src/SimpleWalletManager.ts +526 -0
- package/src/Wallet.ts +1169 -0
- package/src/WalletAuthenticationManager.ts +153 -0
- package/src/WalletLogger.ts +213 -0
- package/src/WalletPermissionsManager.ts +3660 -0
- package/src/WalletSettingsManager.ts +114 -0
- package/src/__tests/CWIStyleWalletManager.test.d.ts.map +1 -0
- package/src/__tests/CWIStyleWalletManager.test.js.map +1 -0
- package/src/__tests/CWIStyleWalletManager.test.ts +675 -0
- package/src/__tests/WalletPermissionsManager.callbacks.test.ts +323 -0
- package/src/__tests/WalletPermissionsManager.checks.test.ts +844 -0
- package/src/__tests/WalletPermissionsManager.encryption.test.ts +412 -0
- package/src/__tests/WalletPermissionsManager.fixtures.ts +307 -0
- package/src/__tests/WalletPermissionsManager.flows.test.ts +462 -0
- package/src/__tests/WalletPermissionsManager.initialization.test.ts +300 -0
- package/src/__tests/WalletPermissionsManager.pmodules.test.ts +798 -0
- package/src/__tests/WalletPermissionsManager.proxying.test.ts +724 -0
- package/src/__tests/WalletPermissionsManager.tokens.test.ts +503 -0
- package/src/index.all.ts +27 -0
- package/src/index.client.ts +25 -0
- package/src/index.mobile.ts +21 -0
- package/src/index.ts +1 -0
- package/src/monitor/Monitor.ts +412 -0
- package/src/monitor/MonitorDaemon.ts +188 -0
- package/src/monitor/README.md +3 -0
- package/src/monitor/__test/MonitorDaemon.man.test.ts +45 -0
- package/src/monitor/tasks/TaskCheckForProofs.ts +243 -0
- package/src/monitor/tasks/TaskCheckNoSends.ts +73 -0
- package/src/monitor/tasks/TaskClock.ts +33 -0
- package/src/monitor/tasks/TaskFailAbandoned.ts +54 -0
- package/src/monitor/tasks/TaskMonitorCallHistory.ts +26 -0
- package/src/monitor/tasks/TaskNewHeader.ts +93 -0
- package/src/monitor/tasks/TaskPurge.ts +68 -0
- package/src/monitor/tasks/TaskReorg.ts +89 -0
- package/src/monitor/tasks/TaskReviewStatus.ts +48 -0
- package/src/monitor/tasks/TaskSendWaiting.ts +122 -0
- package/src/monitor/tasks/TaskSyncWhenIdle.ts +26 -0
- package/src/monitor/tasks/TaskUnFail.ts +151 -0
- package/src/monitor/tasks/WalletMonitorTask.ts +47 -0
- package/src/sdk/CertOpsWallet.ts +18 -0
- package/src/sdk/PrivilegedKeyManager.ts +372 -0
- package/src/sdk/README.md +13 -0
- package/src/sdk/WERR_errors.ts +234 -0
- package/src/sdk/WalletError.ts +170 -0
- package/src/sdk/WalletErrorFromJson.ts +80 -0
- package/src/sdk/WalletServices.interfaces.ts +700 -0
- package/src/sdk/WalletSigner.interfaces.ts +11 -0
- package/src/sdk/WalletStorage.interfaces.ts +606 -0
- package/src/sdk/__test/CertificateLifeCycle.test.ts +131 -0
- package/src/sdk/__test/PrivilegedKeyManager.test.ts +738 -0
- package/src/sdk/__test/WalletError.test.ts +318 -0
- package/src/sdk/__test/validationHelpers.test.ts +21 -0
- package/src/sdk/index.ts +10 -0
- package/src/sdk/types.ts +226 -0
- package/src/services/README.md +11 -0
- package/src/services/ServiceCollection.ts +248 -0
- package/src/services/Services.ts +603 -0
- package/src/services/__tests/ARC.man.test.ts +123 -0
- package/src/services/__tests/ARC.timeout.man.test.ts +79 -0
- package/src/services/__tests/ArcGorillaPool.man.test.ts +108 -0
- package/src/services/__tests/arcServices.test.ts +8 -0
- package/src/services/__tests/bitrails.test.ts +56 -0
- package/src/services/__tests/getMerklePath.test.ts +15 -0
- package/src/services/__tests/getRawTx.test.ts +13 -0
- package/src/services/__tests/postBeef.test.ts +104 -0
- package/src/services/__tests/verifyBeef.test.ts +50 -0
- package/src/services/chaintracker/BHServiceClient.ts +212 -0
- package/src/services/chaintracker/ChaintracksChainTracker.ts +71 -0
- package/src/services/chaintracker/__tests/ChaintracksChainTracker.test.ts +33 -0
- package/src/services/chaintracker/__tests/ChaintracksServiceClient.test.ts +29 -0
- package/src/services/chaintracker/chaintracks/Api/BlockHeaderApi.ts +72 -0
- package/src/services/chaintracker/chaintracks/Api/BulkIngestorApi.ts +83 -0
- package/src/services/chaintracker/chaintracks/Api/BulkStorageApi.ts +92 -0
- package/src/services/chaintracker/chaintracks/Api/ChaintracksApi.ts +64 -0
- package/src/services/chaintracker/chaintracks/Api/ChaintracksClientApi.ts +189 -0
- package/src/services/chaintracker/chaintracks/Api/ChaintracksFetchApi.ts +18 -0
- package/src/services/chaintracker/chaintracks/Api/ChaintracksFsApi.ts +58 -0
- package/src/services/chaintracker/chaintracks/Api/ChaintracksStorageApi.ts +386 -0
- package/src/services/chaintracker/chaintracks/Api/LiveIngestorApi.ts +25 -0
- package/src/services/chaintracker/chaintracks/Chaintracks.ts +609 -0
- package/src/services/chaintracker/chaintracks/ChaintracksService.ts +199 -0
- package/src/services/chaintracker/chaintracks/ChaintracksServiceClient.ts +154 -0
- package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorBase.ts +176 -0
- package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDN.ts +174 -0
- package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDNBabbage.ts +18 -0
- package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorWhatsOnChainCdn.ts +113 -0
- package/src/services/chaintracker/chaintracks/Ingest/BulkIngestorWhatsOnChainWs.ts +81 -0
- package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorBase.ts +86 -0
- package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorTeranodeP2P.ts +59 -0
- package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorWhatsOnChainPoll.ts +104 -0
- package/src/services/chaintracker/chaintracks/Ingest/LiveIngestorWhatsOnChainWs.ts +66 -0
- package/src/services/chaintracker/chaintracks/Ingest/WhatsOnChainIngestorWs.ts +566 -0
- package/src/services/chaintracker/chaintracks/Ingest/WhatsOnChainServices.ts +219 -0
- package/src/services/chaintracker/chaintracks/Ingest/__tests/BulkIngestorCDNBabbage.test.ts +54 -0
- package/src/services/chaintracker/chaintracks/Ingest/__tests/LiveIngestorWhatsOnChainPoll.test.ts +33 -0
- package/src/services/chaintracker/chaintracks/Ingest/__tests/WhatsOnChainServices.test.ts +124 -0
- package/src/services/chaintracker/chaintracks/Storage/BulkStorageBase.ts +92 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksKnexMigrations.ts +104 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageBase.ts +382 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageIdb.ts +574 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageKnex.ts +438 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageMemory.ts +29 -0
- package/src/services/chaintracker/chaintracks/Storage/ChaintracksStorageNoDb.ts +304 -0
- package/src/services/chaintracker/chaintracks/Storage/__tests/ChaintracksStorageIdb.test.ts +102 -0
- package/src/services/chaintracker/chaintracks/Storage/__tests/ChaintracksStorageKnex.test.ts +45 -0
- package/src/services/chaintracker/chaintracks/__tests/Chaintracks.test.ts +77 -0
- package/src/services/chaintracker/chaintracks/__tests/ChaintracksClientApi.test.ts +192 -0
- package/src/services/chaintracker/chaintracks/__tests/LocalCdnServer.ts +75 -0
- package/src/services/chaintracker/chaintracks/__tests/createIdbChaintracks.test.ts +62 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNetBlockHeaders.json +1 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_0.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_1.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_2.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest349/mainNet_3.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNetBlockHeaders.json +1 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_0.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_1.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_2.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest379/mainNet_3.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNetBlockHeaders.json +1 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_0.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_1.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_2.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest399/mainNet_3.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNetBlockHeaders.json +1 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_0.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_1.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_2.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_3.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest402/mainNet_4.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNetBlockHeaders.json +1 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_0.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_1.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_2.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_3.headers +0 -0
- package/src/services/chaintracker/chaintracks/__tests/data/cdnTest499/mainNet_4.headers +0 -0
- package/src/services/chaintracker/chaintracks/createDefaultIdbChaintracksOptions.ts +92 -0
- package/src/services/chaintracker/chaintracks/createDefaultKnexChaintracksOptions.ts +111 -0
- package/src/services/chaintracker/chaintracks/createDefaultNoDbChaintracksOptions.ts +91 -0
- package/src/services/chaintracker/chaintracks/createIdbChaintracks.ts +60 -0
- package/src/services/chaintracker/chaintracks/createKnexChaintracks.ts +65 -0
- package/src/services/chaintracker/chaintracks/createNoDbChaintracks.ts +60 -0
- package/src/services/chaintracker/chaintracks/index.all.ts +12 -0
- package/src/services/chaintracker/chaintracks/index.client.ts +4 -0
- package/src/services/chaintracker/chaintracks/index.mobile.ts +37 -0
- package/src/services/chaintracker/chaintracks/util/BulkFileDataManager.ts +975 -0
- package/src/services/chaintracker/chaintracks/util/BulkFileDataReader.ts +60 -0
- package/src/services/chaintracker/chaintracks/util/BulkFilesReader.ts +336 -0
- package/src/services/chaintracker/chaintracks/util/BulkHeaderFile.ts +247 -0
- package/src/services/chaintracker/chaintracks/util/ChaintracksFetch.ts +69 -0
- package/src/services/chaintracker/chaintracks/util/ChaintracksFs.ts +141 -0
- package/src/services/chaintracker/chaintracks/util/HeightRange.ts +153 -0
- package/src/services/chaintracker/chaintracks/util/SingleWriterMultiReaderLock.ts +76 -0
- package/src/services/chaintracker/chaintracks/util/__tests/BulkFileDataManager.test.ts +304 -0
- package/src/services/chaintracker/chaintracks/util/__tests/ChaintracksFetch.test.ts +60 -0
- package/src/services/chaintracker/chaintracks/util/__tests/HeightRange.test.ts +67 -0
- package/src/services/chaintracker/chaintracks/util/__tests/SingleWriterMultiReaderLock.test.ts +49 -0
- package/src/services/chaintracker/chaintracks/util/blockHeaderUtilities.ts +573 -0
- package/src/services/chaintracker/chaintracks/util/dirtyHashes.ts +29 -0
- package/src/services/chaintracker/chaintracks/util/validBulkHeaderFilesByFileHash.ts +432 -0
- package/src/services/chaintracker/index.all.ts +4 -0
- package/src/services/chaintracker/index.client.ts +4 -0
- package/src/services/chaintracker/index.mobile.ts +4 -0
- package/src/services/createDefaultWalletServicesOptions.ts +77 -0
- package/src/services/index.ts +1 -0
- package/src/services/processingErrors/arcSuccessError.json +76 -0
- package/src/services/providers/ARC.ts +350 -0
- package/src/services/providers/Bitails.ts +256 -0
- package/src/services/providers/SdkWhatsOnChain.ts +83 -0
- package/src/services/providers/WhatsOnChain.ts +883 -0
- package/src/services/providers/__tests/WhatsOnChain.test.ts +242 -0
- package/src/services/providers/__tests/exchangeRates.test.ts +18 -0
- package/src/services/providers/exchangeRates.ts +265 -0
- package/src/services/providers/getBeefForTxid.ts +369 -0
- package/src/signer/README.md +5 -0
- package/src/signer/WalletSigner.ts +17 -0
- package/src/signer/methods/acquireDirectCertificate.ts +52 -0
- package/src/signer/methods/buildSignableTransaction.ts +183 -0
- package/src/signer/methods/completeSignedTransaction.ts +117 -0
- package/src/signer/methods/createAction.ts +172 -0
- package/src/signer/methods/internalizeAction.ts +106 -0
- package/src/signer/methods/proveCertificate.ts +43 -0
- package/src/signer/methods/signAction.ts +54 -0
- package/src/storage/README.md +14 -0
- package/src/storage/StorageIdb.ts +2304 -0
- package/src/storage/StorageKnex.ts +1425 -0
- package/src/storage/StorageProvider.ts +810 -0
- package/src/storage/StorageReader.ts +194 -0
- package/src/storage/StorageReaderWriter.ts +432 -0
- package/src/storage/StorageSyncReader.ts +34 -0
- package/src/storage/WalletStorageManager.ts +943 -0
- package/src/storage/__test/StorageIdb.test.ts +43 -0
- package/src/storage/__test/WalletStorageManager.test.ts +275 -0
- package/src/storage/__test/adminStats.man.test.ts +89 -0
- package/src/storage/__test/getBeefForTransaction.test.ts +385 -0
- package/src/storage/index.all.ts +11 -0
- package/src/storage/index.client.ts +7 -0
- package/src/storage/index.mobile.ts +6 -0
- package/src/storage/methods/ListActionsSpecOp.ts +70 -0
- package/src/storage/methods/ListOutputsSpecOp.ts +129 -0
- package/src/storage/methods/__test/GenerateChange/generateChangeSdk.test.ts +1057 -0
- package/src/storage/methods/__test/GenerateChange/randomValsUsed1.ts +20 -0
- package/src/storage/methods/__test/offsetKey.test.ts +274 -0
- package/src/storage/methods/attemptToPostReqsToNetwork.ts +389 -0
- package/src/storage/methods/createAction.ts +947 -0
- package/src/storage/methods/generateChange.ts +556 -0
- package/src/storage/methods/getBeefForTransaction.ts +139 -0
- package/src/storage/methods/getSyncChunk.ts +293 -0
- package/src/storage/methods/internalizeAction.ts +562 -0
- package/src/storage/methods/listActionsIdb.ts +183 -0
- package/src/storage/methods/listActionsKnex.ts +226 -0
- package/src/storage/methods/listCertificates.ts +73 -0
- package/src/storage/methods/listOutputsIdb.ts +203 -0
- package/src/storage/methods/listOutputsKnex.ts +263 -0
- package/src/storage/methods/offsetKey.ts +89 -0
- package/src/storage/methods/processAction.ts +420 -0
- package/src/storage/methods/purgeData.ts +251 -0
- package/src/storage/methods/purgeDataIdb.ts +10 -0
- package/src/storage/methods/reviewStatus.ts +101 -0
- package/src/storage/methods/reviewStatusIdb.ts +43 -0
- package/src/storage/methods/utils.Buffer.ts +33 -0
- package/src/storage/methods/utils.ts +56 -0
- package/src/storage/remoting/StorageClient.ts +567 -0
- package/src/storage/remoting/StorageMobile.ts +544 -0
- package/src/storage/remoting/StorageServer.ts +291 -0
- package/src/storage/remoting/__test/StorageClient.test.ts +113 -0
- package/src/storage/schema/KnexMigrations.ts +489 -0
- package/src/storage/schema/StorageIdbSchema.ts +150 -0
- package/src/storage/schema/entities/EntityBase.ts +210 -0
- package/src/storage/schema/entities/EntityCertificate.ts +188 -0
- package/src/storage/schema/entities/EntityCertificateField.ts +136 -0
- package/src/storage/schema/entities/EntityCommission.ts +148 -0
- package/src/storage/schema/entities/EntityOutput.ts +290 -0
- package/src/storage/schema/entities/EntityOutputBasket.ts +153 -0
- package/src/storage/schema/entities/EntityOutputTag.ts +121 -0
- package/src/storage/schema/entities/EntityOutputTagMap.ts +123 -0
- package/src/storage/schema/entities/EntityProvenTx.ts +319 -0
- package/src/storage/schema/entities/EntityProvenTxReq.ts +580 -0
- package/src/storage/schema/entities/EntitySyncState.ts +389 -0
- package/src/storage/schema/entities/EntityTransaction.ts +306 -0
- package/src/storage/schema/entities/EntityTxLabel.ts +121 -0
- package/src/storage/schema/entities/EntityTxLabelMap.ts +123 -0
- package/src/storage/schema/entities/EntityUser.ts +112 -0
- package/src/storage/schema/entities/MergeEntity.ts +73 -0
- package/src/storage/schema/entities/__tests/CertificateFieldTests.test.ts +353 -0
- package/src/storage/schema/entities/__tests/CertificateTests.test.ts +354 -0
- package/src/storage/schema/entities/__tests/CommissionTests.test.ts +371 -0
- package/src/storage/schema/entities/__tests/OutputBasketTests.test.ts +278 -0
- package/src/storage/schema/entities/__tests/OutputTagMapTests.test.ts +242 -0
- package/src/storage/schema/entities/__tests/OutputTagTests.test.ts +288 -0
- package/src/storage/schema/entities/__tests/OutputTests.test.ts +464 -0
- package/src/storage/schema/entities/__tests/ProvenTxReqTests.test.ts +340 -0
- package/src/storage/schema/entities/__tests/ProvenTxTests.test.ts +504 -0
- package/src/storage/schema/entities/__tests/SyncStateTests.test.ts +288 -0
- package/src/storage/schema/entities/__tests/TransactionTests.test.ts +604 -0
- package/src/storage/schema/entities/__tests/TxLabelMapTests.test.ts +361 -0
- package/src/storage/schema/entities/__tests/TxLabelTests.test.ts +198 -0
- package/src/storage/schema/entities/__tests/stampLogTests.test.ts +90 -0
- package/src/storage/schema/entities/__tests/usersTests.test.ts +340 -0
- package/src/storage/schema/entities/index.ts +16 -0
- package/src/storage/schema/tables/TableCertificate.ts +21 -0
- package/src/storage/schema/tables/TableCertificateField.ts +12 -0
- package/src/storage/schema/tables/TableCommission.ts +13 -0
- package/src/storage/schema/tables/TableMonitorEvent.ts +9 -0
- package/src/storage/schema/tables/TableOutput.ts +64 -0
- package/src/storage/schema/tables/TableOutputBasket.ts +12 -0
- package/src/storage/schema/tables/TableOutputTag.ts +10 -0
- package/src/storage/schema/tables/TableOutputTagMap.ts +9 -0
- package/src/storage/schema/tables/TableProvenTx.ts +14 -0
- package/src/storage/schema/tables/TableProvenTxReq.ts +65 -0
- package/src/storage/schema/tables/TableSettings.ts +17 -0
- package/src/storage/schema/tables/TableSyncState.ts +18 -0
- package/src/storage/schema/tables/TableTransaction.ts +54 -0
- package/src/storage/schema/tables/TableTxLabel.ts +10 -0
- package/src/storage/schema/tables/TableTxLabelMap.ts +9 -0
- package/src/storage/schema/tables/TableUser.ts +16 -0
- package/src/storage/schema/tables/index.ts +16 -0
- package/src/storage/sync/StorageMySQLDojoReader.ts +696 -0
- package/src/storage/sync/index.ts +1 -0
- package/src/utility/Format.ts +133 -0
- package/src/utility/README.md +3 -0
- package/src/utility/ReaderUint8Array.ts +187 -0
- package/src/utility/ScriptTemplateBRC29.ts +73 -0
- package/src/utility/__tests/utilityHelpers.noBuffer.test.ts +109 -0
- package/src/utility/aggregateResults.ts +68 -0
- package/src/utility/identityUtils.ts +159 -0
- package/src/utility/index.all.ts +7 -0
- package/src/utility/index.client.ts +7 -0
- package/src/utility/parseTxScriptOffsets.ts +29 -0
- package/src/utility/stampLog.ts +69 -0
- package/src/utility/tscProofToMerklePath.ts +48 -0
- package/src/utility/utilityHelpers.buffer.ts +34 -0
- package/src/utility/utilityHelpers.noBuffer.ts +60 -0
- package/src/utility/utilityHelpers.ts +275 -0
- package/src/wab-client/WABClient.ts +94 -0
- package/src/wab-client/__tests/WABClient.man.test.ts +59 -0
- package/src/wab-client/auth-method-interactors/AuthMethodInteractor.ts +47 -0
- package/src/wab-client/auth-method-interactors/DevConsoleInteractor.ts +73 -0
- package/src/wab-client/auth-method-interactors/PersonaIDInteractor.ts +35 -0
- package/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.ts +72 -0
- package/syncVersions.js +71 -0
- package/test/Wallet/StorageClient/storageClient.man.test.ts +75 -0
- package/test/Wallet/action/abortAction.test.ts +47 -0
- package/test/Wallet/action/createAction.test.ts +299 -0
- package/test/Wallet/action/createAction2.test.ts +1273 -0
- package/test/Wallet/action/createActionToGenerateBeefs.man.test.ts +293 -0
- package/test/Wallet/action/internalizeAction.a.test.ts +286 -0
- package/test/Wallet/action/internalizeAction.test.ts +682 -0
- package/test/Wallet/action/relinquishOutput.test.ts +37 -0
- package/test/Wallet/certificate/acquireCertificate.test.ts +298 -0
- package/test/Wallet/certificate/listCertificates.test.ts +346 -0
- package/test/Wallet/construct/Wallet.constructor.test.ts +57 -0
- package/test/Wallet/get/getHeaderForHeight.test.ts +82 -0
- package/test/Wallet/get/getHeight.test.ts +52 -0
- package/test/Wallet/get/getKnownTxids.test.ts +86 -0
- package/test/Wallet/get/getNetwork.test.ts +27 -0
- package/test/Wallet/get/getVersion.test.ts +27 -0
- package/test/Wallet/list/listActions.test.ts +279 -0
- package/test/Wallet/list/listActions2.test.ts +1381 -0
- package/test/Wallet/list/listCertificates.test.ts +118 -0
- package/test/Wallet/list/listOutputs.test.ts +447 -0
- package/test/Wallet/live/walletLive.man.test.ts +521 -0
- package/test/Wallet/local/localWallet.man.test.ts +93 -0
- package/test/Wallet/local/localWallet2.man.test.ts +277 -0
- package/test/Wallet/signAction/mountaintop.man.test.ts +130 -0
- package/test/Wallet/specOps/specOps.man.test.ts +220 -0
- package/test/Wallet/support/janitor.man.test.ts +40 -0
- package/test/Wallet/support/operations.man.test.ts +407 -0
- package/test/Wallet/support/reqErrorReview.2025.05.06.man.test.ts +347 -0
- package/test/Wallet/sync/Wallet.sync.test.ts +215 -0
- package/test/Wallet/sync/Wallet.updateWalletLegacyTestData.man.test.ts +203 -0
- package/test/Wallet/sync/setActive.test.ts +170 -0
- package/test/WalletClient/LocalKVStore.man.test.ts +114 -0
- package/test/WalletClient/WERR.man.test.ts +35 -0
- package/test/bsv-ts-sdk/LocalKVStore.test.ts +102 -0
- package/test/checkDB.ts +57 -0
- package/test/checkdb +0 -0
- package/test/examples/backup.man.test.ts +59 -0
- package/test/examples/pushdrop.test.ts +282 -0
- package/test/monitor/Monitor.test.ts +620 -0
- package/test/services/Services.test.ts +263 -0
- package/test/storage/KnexMigrations.test.ts +86 -0
- package/test/storage/StorageMySQLDojoReader.man.test.ts +60 -0
- package/test/storage/count.test.ts +177 -0
- package/test/storage/find.test.ts +195 -0
- package/test/storage/findLegacy.test.ts +67 -0
- package/test/storage/idb/allocateChange.test.ts +251 -0
- package/test/storage/idb/count.test.ts +158 -0
- package/test/storage/idb/find.test.ts +177 -0
- package/test/storage/idb/idbSpeed.test.ts +36 -0
- package/test/storage/idb/insert.test.ts +268 -0
- package/test/storage/idb/transactionAbort.test.ts +108 -0
- package/test/storage/idb/update.test.ts +999 -0
- package/test/storage/insert.test.ts +278 -0
- package/test/storage/update.test.ts +1021 -0
- package/test/storage/update2.test.ts +897 -0
- package/test/utils/TestUtilsWalletStorage.ts +2526 -0
- package/test/utils/localWalletMethods.ts +363 -0
- package/test/utils/removeFailedFromDatabase.sql +17 -0
- package/ts2md.json +44 -0
- package/tsconfig.all.json +31 -0
- package/tsconfig.client.json +29 -0
- package/tsconfig.json +17 -0
- package/tsconfig.mobile.json +28 -0
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
import { Validation, WalletLoggerInterface } from '@bsv/sdk'
|
|
2
|
+
import { WalletError } from '../../sdk/WalletError'
|
|
3
|
+
import { StorageFeeModel } from '../../sdk/WalletStorage.interfaces'
|
|
4
|
+
import { WERR_INSUFFICIENT_FUNDS, WERR_INTERNAL, WERR_INVALID_PARAMETER } from '../../sdk/WERR_errors'
|
|
5
|
+
import { validateStorageFeeModel } from '../StorageProvider'
|
|
6
|
+
import { transactionSize } from './utils'
|
|
7
|
+
import { Wallet, WalletLogger } from '../../index.client'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* An output of this satoshis amount will be adjusted to the largest fundable amount.
|
|
11
|
+
*/
|
|
12
|
+
export const maxPossibleSatoshis = 2099999999999999
|
|
13
|
+
|
|
14
|
+
export interface GenerateChangeSdkResult {
|
|
15
|
+
allocatedChangeInputs: GenerateChangeSdkChangeInput[]
|
|
16
|
+
changeOutputs: GenerateChangeSdkChangeOutput[]
|
|
17
|
+
size: number
|
|
18
|
+
fee: number
|
|
19
|
+
satsPerKb: number
|
|
20
|
+
maxPossibleSatoshisAdjustment?: {
|
|
21
|
+
fixedOutputIndex: number
|
|
22
|
+
satoshis: number
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Simplifications:
|
|
28
|
+
* - only support one change type with fixed length scripts.
|
|
29
|
+
* - only support satsPerKb fee model.
|
|
30
|
+
*
|
|
31
|
+
* Confirms for each availbleChange output that it remains available as they are allocated and selects alternate if not.
|
|
32
|
+
*
|
|
33
|
+
* @param params
|
|
34
|
+
* @returns
|
|
35
|
+
*/
|
|
36
|
+
export async function generateChangeSdk(
|
|
37
|
+
params: GenerateChangeSdkParams,
|
|
38
|
+
allocateChangeInput: (
|
|
39
|
+
targetSatoshis: number,
|
|
40
|
+
exactSatoshis?: number
|
|
41
|
+
) => Promise<GenerateChangeSdkChangeInput | undefined>,
|
|
42
|
+
releaseChangeInput: (outputId: number) => Promise<void>,
|
|
43
|
+
logger?: WalletLoggerInterface
|
|
44
|
+
): Promise<GenerateChangeSdkResult> {
|
|
45
|
+
if (params.noLogging === false) logGenerateChangeSdkParams(params)
|
|
46
|
+
|
|
47
|
+
const r: GenerateChangeSdkResult = {
|
|
48
|
+
allocatedChangeInputs: [],
|
|
49
|
+
changeOutputs: [],
|
|
50
|
+
size: 0,
|
|
51
|
+
fee: 0,
|
|
52
|
+
satsPerKb: 0
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// eslint-disable-next-line no-useless-catch
|
|
56
|
+
try {
|
|
57
|
+
const vgcpr = validateGenerateChangeSdkParams(params)
|
|
58
|
+
|
|
59
|
+
const satsPerKb = params.feeModel.value || 0
|
|
60
|
+
|
|
61
|
+
const randomVals = [...(params.randomVals || [])]
|
|
62
|
+
const randomValsUsed: number[] = []
|
|
63
|
+
|
|
64
|
+
const nextRandomVal = (): number => {
|
|
65
|
+
let val = 0
|
|
66
|
+
if (!randomVals || randomVals.length === 0) {
|
|
67
|
+
val = Math.random()
|
|
68
|
+
} else {
|
|
69
|
+
val = randomVals.shift() || 0
|
|
70
|
+
randomVals.push(val)
|
|
71
|
+
}
|
|
72
|
+
// Capture random sequence used if not supplied
|
|
73
|
+
randomValsUsed.push(val)
|
|
74
|
+
return val
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @returns a random integer betweenn min and max, inclussive.
|
|
79
|
+
*/
|
|
80
|
+
const rand = (min: number, max: number): number => {
|
|
81
|
+
if (max < min) throw new WERR_INVALID_PARAMETER('max', `less than min (${min}). max is (${max})`)
|
|
82
|
+
return Math.floor(nextRandomVal() * (max - min + 1) + min)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const fixedInputs = params.fixedInputs
|
|
86
|
+
const fixedOutputs = params.fixedOutputs
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @returns sum of transaction fixedInputs satoshis and fundingInputs satoshis
|
|
90
|
+
*/
|
|
91
|
+
const funding = (): number => {
|
|
92
|
+
return (
|
|
93
|
+
fixedInputs.reduce((a, e) => a + e.satoshis, 0) + r.allocatedChangeInputs.reduce((a, e) => a + e.satoshis, 0)
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @returns sum of transaction fixedOutputs satoshis
|
|
99
|
+
*/
|
|
100
|
+
const spending = (): number => {
|
|
101
|
+
return fixedOutputs.reduce((a, e) => a + e.satoshis, 0)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @returns sum of transaction changeOutputs satoshis
|
|
106
|
+
*/
|
|
107
|
+
const change = (): number => {
|
|
108
|
+
return r.changeOutputs.reduce((a, e) => a + e.satoshis, 0)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const fee = (): number => funding() - spending() - change()
|
|
112
|
+
|
|
113
|
+
const size = (addedChangeInputs?: number, addedChangeOutputs?: number): number => {
|
|
114
|
+
const inputScriptLengths = [
|
|
115
|
+
...fixedInputs.map(x => x.unlockingScriptLength),
|
|
116
|
+
...Array(r.allocatedChangeInputs.length + (addedChangeInputs || 0)).fill(params.changeUnlockingScriptLength)
|
|
117
|
+
]
|
|
118
|
+
const outputScriptLengths = [
|
|
119
|
+
...fixedOutputs.map(x => x.lockingScriptLength),
|
|
120
|
+
...Array(r.changeOutputs.length + (addedChangeOutputs || 0)).fill(params.changeLockingScriptLength)
|
|
121
|
+
]
|
|
122
|
+
const size = transactionSize(inputScriptLengths, outputScriptLengths)
|
|
123
|
+
return size
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @returns the target fee required for the transaction as currently configured under feeModel.
|
|
128
|
+
*/
|
|
129
|
+
const feeTarget = (addedChangeInputs?: number, addedChangeOutputs?: number): number => {
|
|
130
|
+
const fee = Math.ceil((size(addedChangeInputs, addedChangeOutputs) / 1000) * satsPerKb)
|
|
131
|
+
return fee
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @returns the current excess fee for the transaction as currently configured.
|
|
136
|
+
*
|
|
137
|
+
* This is funding() - spending() - change() - feeTarget()
|
|
138
|
+
*
|
|
139
|
+
* The goal is an excess fee of zero.
|
|
140
|
+
*
|
|
141
|
+
* A positive value is okay if the cost of an additional change output is greater.
|
|
142
|
+
*
|
|
143
|
+
* A negative value means the transaction is under funded, or over spends, and may be rejected.
|
|
144
|
+
*/
|
|
145
|
+
const feeExcess = (addedChangeInputs?: number, addedChangeOutputs?: number): number => {
|
|
146
|
+
const fe = funding() - spending() - change() - feeTarget(addedChangeInputs, addedChangeOutputs)
|
|
147
|
+
if (!addedChangeInputs && !addedChangeOutputs) feeExcessNow = fe
|
|
148
|
+
return fe
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// The most recent feeExcess()
|
|
152
|
+
let feeExcessNow = 0
|
|
153
|
+
feeExcess()
|
|
154
|
+
|
|
155
|
+
const hasTargetNetCount = params.targetNetCount !== undefined
|
|
156
|
+
const targetNetCount = params.targetNetCount || 0
|
|
157
|
+
|
|
158
|
+
// current net change in count of change outputs
|
|
159
|
+
const netChangeCount = (): number => {
|
|
160
|
+
return r.changeOutputs.length - r.allocatedChangeInputs.length
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const addOutputToBalanceNewInput = (): boolean => {
|
|
164
|
+
if (!hasTargetNetCount) return false
|
|
165
|
+
return netChangeCount() - 1 < targetNetCount
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const releaseAllocatedChangeInputs = async (): Promise<void> => {
|
|
169
|
+
while (r.allocatedChangeInputs.length > 0) {
|
|
170
|
+
const i = r.allocatedChangeInputs.pop()
|
|
171
|
+
if (i) {
|
|
172
|
+
await releaseChangeInput(i.outputId)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
feeExcessNow = feeExcess()
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// If we'd like to have more change outputs create them now.
|
|
179
|
+
// They may be removed if it turns out we can't fund them.
|
|
180
|
+
while (
|
|
181
|
+
(hasTargetNetCount && targetNetCount > netChangeCount()) ||
|
|
182
|
+
(r.changeOutputs.length === 0 && feeExcess() > 0)
|
|
183
|
+
) {
|
|
184
|
+
r.changeOutputs.push({
|
|
185
|
+
satoshis: r.changeOutputs.length === 0 ? params.changeFirstSatoshis : params.changeInitialSatoshis,
|
|
186
|
+
lockingScriptLength: params.changeLockingScriptLength
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const fundTransaction = async (): Promise<void> => {
|
|
191
|
+
let removingOutputs = false
|
|
192
|
+
|
|
193
|
+
const attemptToFundTransaction = async (): Promise<boolean> => {
|
|
194
|
+
if (feeExcess() > 0) return true
|
|
195
|
+
|
|
196
|
+
let exactSatoshis: number | undefined = undefined
|
|
197
|
+
if (!hasTargetNetCount && r.changeOutputs.length === 0) {
|
|
198
|
+
exactSatoshis = -feeExcess(1)
|
|
199
|
+
}
|
|
200
|
+
const ao = addOutputToBalanceNewInput() ? 1 : 0
|
|
201
|
+
const targetSatoshis = -feeExcess(1, ao) + (ao === 1 ? 2 * params.changeInitialSatoshis : 0)
|
|
202
|
+
|
|
203
|
+
const allocatedChangeInput = await allocateChangeInput(targetSatoshis, exactSatoshis)
|
|
204
|
+
|
|
205
|
+
if (!allocatedChangeInput) {
|
|
206
|
+
// Unable to add another funding change input
|
|
207
|
+
return false
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
r.allocatedChangeInputs.push(allocatedChangeInput)
|
|
211
|
+
|
|
212
|
+
if (!removingOutputs && feeExcess() > 0) {
|
|
213
|
+
if (ao == 1 || r.changeOutputs.length === 0) {
|
|
214
|
+
r.changeOutputs.push({
|
|
215
|
+
satoshis: Math.min(
|
|
216
|
+
feeExcess(),
|
|
217
|
+
r.changeOutputs.length === 0 ? params.changeFirstSatoshis : params.changeInitialSatoshis
|
|
218
|
+
),
|
|
219
|
+
lockingScriptLength: params.changeLockingScriptLength
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return true
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
for (;;) {
|
|
227
|
+
// This is the starvation loop, drops change outputs one at a time if unable to fund them...
|
|
228
|
+
await releaseAllocatedChangeInputs()
|
|
229
|
+
|
|
230
|
+
while (feeExcess() < 0) {
|
|
231
|
+
// This is the funding loop, add one change input at a time...
|
|
232
|
+
const ok = await attemptToFundTransaction()
|
|
233
|
+
if (!ok) break
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Done if blanced overbalanced or impossible (all funding applied, all change outputs removed).
|
|
237
|
+
if (feeExcess() >= 0 || r.changeOutputs.length === 0) break
|
|
238
|
+
|
|
239
|
+
removingOutputs = true
|
|
240
|
+
while (r.changeOutputs.length > 0 && feeExcess() < 0) {
|
|
241
|
+
r.changeOutputs.pop()
|
|
242
|
+
}
|
|
243
|
+
if (feeExcess() < 0)
|
|
244
|
+
// Not enough available funding even if no change outputs
|
|
245
|
+
break
|
|
246
|
+
// At this point we have a funded transaction, but there may be change outputs that are each costing as change input,
|
|
247
|
+
// resulting in pointless churn of change outputs.
|
|
248
|
+
// And remove change inputs that funded only a single change output (along with that output)...
|
|
249
|
+
const changeInputs = [...r.allocatedChangeInputs]
|
|
250
|
+
while (changeInputs.length > 1 && r.changeOutputs.length > 1) {
|
|
251
|
+
const lastOutput = r.changeOutputs.slice(-1)[0]
|
|
252
|
+
const i = changeInputs.findIndex(ci => ci.satoshis <= lastOutput.satoshis)
|
|
253
|
+
if (i < 0) break
|
|
254
|
+
r.changeOutputs.pop()
|
|
255
|
+
changeInputs.splice(i, 1)
|
|
256
|
+
}
|
|
257
|
+
// and try again...
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Add funding to achieve a non-negative feeExcess value, if necessary.
|
|
263
|
+
*/
|
|
264
|
+
await fundTransaction()
|
|
265
|
+
|
|
266
|
+
if (feeExcess() < 0 && vgcpr.hasMaxPossibleOutput !== undefined) {
|
|
267
|
+
// Reduce the fixed output with satoshis of maxPossibleSatoshis to what will just fund the transaction...
|
|
268
|
+
if (fixedOutputs[vgcpr.hasMaxPossibleOutput].satoshis !== maxPossibleSatoshis) throw new WERR_INTERNAL()
|
|
269
|
+
fixedOutputs[vgcpr.hasMaxPossibleOutput].satoshis += feeExcess()
|
|
270
|
+
r.maxPossibleSatoshisAdjustment = {
|
|
271
|
+
fixedOutputIndex: vgcpr.hasMaxPossibleOutput,
|
|
272
|
+
satoshis: fixedOutputs[vgcpr.hasMaxPossibleOutput].satoshis
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Trigger an account funding event if we don't have enough to cover this transaction.
|
|
278
|
+
*/
|
|
279
|
+
if (feeExcess() < 0) {
|
|
280
|
+
const werr = new WERR_INSUFFICIENT_FUNDS(spending() + feeTarget(), -feeExcessNow)
|
|
281
|
+
logger?.error(`throwing WERR_INSUFFICIENT_FUNDS moreSatoshisNeeded ${werr.moreSatoshisNeeded}`)
|
|
282
|
+
await releaseAllocatedChangeInputs()
|
|
283
|
+
throw werr
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* If needed, seek funding to avoid overspending on fees without a change output to recapture it.
|
|
288
|
+
*/
|
|
289
|
+
if (r.changeOutputs.length === 0 && feeExcessNow > 0) {
|
|
290
|
+
await releaseAllocatedChangeInputs()
|
|
291
|
+
throw new WERR_INSUFFICIENT_FUNDS(spending() + feeTarget(), params.changeFirstSatoshis)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Distribute the excess fees across the changeOutputs added.
|
|
296
|
+
*/
|
|
297
|
+
while (r.changeOutputs.length > 0 && feeExcessNow > 0) {
|
|
298
|
+
if (r.changeOutputs.length === 1) {
|
|
299
|
+
r.changeOutputs[0].satoshis += feeExcessNow
|
|
300
|
+
feeExcessNow = 0
|
|
301
|
+
} else if (r.changeOutputs[0].satoshis < params.changeInitialSatoshis) {
|
|
302
|
+
const sats = Math.min(feeExcessNow, params.changeInitialSatoshis - r.changeOutputs[0].satoshis)
|
|
303
|
+
feeExcessNow -= sats
|
|
304
|
+
r.changeOutputs[0].satoshis += sats
|
|
305
|
+
} else {
|
|
306
|
+
// Distribute a random percentage between 25% and 50% but at least one satoshi
|
|
307
|
+
const sats = Math.max(1, Math.floor((rand(2500, 5000) / 10000) * feeExcessNow))
|
|
308
|
+
feeExcessNow -= sats
|
|
309
|
+
const index = rand(0, r.changeOutputs.length - 1)
|
|
310
|
+
r.changeOutputs[index].satoshis += sats
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
r.size = size()
|
|
315
|
+
;((r.fee = fee()), (r.satsPerKb = satsPerKb))
|
|
316
|
+
|
|
317
|
+
const { ok, log } = validateGenerateChangeSdkResult(params, r)
|
|
318
|
+
if (!ok) {
|
|
319
|
+
throw new WERR_INTERNAL(`generateChangeSdk error: ${log}`)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (r.allocatedChangeInputs.length > 4 && r.changeOutputs.length > 4) {
|
|
323
|
+
console.log('generateChangeSdk_Capture_too_many_ins_and_outs')
|
|
324
|
+
logGenerateChangeSdkParams(params)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return r
|
|
328
|
+
} catch (eu: unknown) {
|
|
329
|
+
const e = WalletError.fromUnknown(eu)
|
|
330
|
+
if (e.code === 'WERR_INSUFFICIENT_FUNDS') throw eu
|
|
331
|
+
|
|
332
|
+
// Capture the params in cloud run log which has a 100k text length limit per line.
|
|
333
|
+
// logGenerateChangeSdkParams(params, eu)
|
|
334
|
+
|
|
335
|
+
throw eu
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function validateGenerateChangeSdkResult(
|
|
340
|
+
params: GenerateChangeSdkParams,
|
|
341
|
+
r: GenerateChangeSdkResult
|
|
342
|
+
): { ok: boolean; log: string } {
|
|
343
|
+
let ok = true
|
|
344
|
+
let log = ''
|
|
345
|
+
const sumIn =
|
|
346
|
+
params.fixedInputs.reduce((a, e) => a + e.satoshis, 0) + r.allocatedChangeInputs.reduce((a, e) => a + e.satoshis, 0)
|
|
347
|
+
const sumOut =
|
|
348
|
+
params.fixedOutputs.reduce((a, e) => a + e.satoshis, 0) + r.changeOutputs.reduce((a, e) => a + e.satoshis, 0)
|
|
349
|
+
if (r.fee && Number.isInteger(r.fee) && r.fee < 0) {
|
|
350
|
+
log += `basic fee error ${r.fee};`
|
|
351
|
+
ok = false
|
|
352
|
+
}
|
|
353
|
+
const feePaid = sumIn - sumOut
|
|
354
|
+
if (feePaid !== r.fee) {
|
|
355
|
+
log += `exact fee error ${feePaid} !== ${r.fee};`
|
|
356
|
+
ok = false
|
|
357
|
+
}
|
|
358
|
+
const feeRequired = Math.ceil(((r.size || 0) / 1000) * (r.satsPerKb || 0))
|
|
359
|
+
if (feeRequired !== r.fee) {
|
|
360
|
+
log += `required fee error ${feeRequired} !== ${r.fee};`
|
|
361
|
+
ok = false
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { ok, log }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function logGenerateChangeSdkParams(params: GenerateChangeSdkParams, eu?: unknown) {
|
|
368
|
+
let s = JSON.stringify(params)
|
|
369
|
+
console.log(`generateChangeSdk params length ${s.length}${eu ? ` error: ${eu}` : ''}`)
|
|
370
|
+
let i = -1
|
|
371
|
+
const maxlen = 99900
|
|
372
|
+
for (;;) {
|
|
373
|
+
i++
|
|
374
|
+
console.log(`generateChangeSdk params ${i} XXX${s.slice(0, maxlen)}XXX`)
|
|
375
|
+
s = s.slice(maxlen)
|
|
376
|
+
if (!s || i > 100) break
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export interface GenerateChangeSdkParams {
|
|
381
|
+
fixedInputs: GenerateChangeSdkInput[]
|
|
382
|
+
fixedOutputs: GenerateChangeSdkOutput[]
|
|
383
|
+
|
|
384
|
+
feeModel: StorageFeeModel
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Target for number of new change outputs added minus number of funding change outputs consumed.
|
|
388
|
+
* If undefined, only a single change output will be added if excess fees must be recaptured.
|
|
389
|
+
*/
|
|
390
|
+
targetNetCount?: number
|
|
391
|
+
/**
|
|
392
|
+
* Satoshi amount to initialize optional new change outputs.
|
|
393
|
+
*/
|
|
394
|
+
changeInitialSatoshis: number
|
|
395
|
+
/**
|
|
396
|
+
* Lowest amount value to assign to a change output.
|
|
397
|
+
* Drop the output if unable to satisfy.
|
|
398
|
+
* default 285
|
|
399
|
+
*/
|
|
400
|
+
changeFirstSatoshis: number
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Fixed change locking script length.
|
|
404
|
+
*
|
|
405
|
+
* For P2PKH template, 25 bytes
|
|
406
|
+
*/
|
|
407
|
+
changeLockingScriptLength: number
|
|
408
|
+
/**
|
|
409
|
+
* Fixed change unlocking script length.
|
|
410
|
+
*
|
|
411
|
+
* For P2PKH template, 107 bytes
|
|
412
|
+
*/
|
|
413
|
+
changeUnlockingScriptLength: number
|
|
414
|
+
|
|
415
|
+
randomVals?: number[]
|
|
416
|
+
noLogging?: boolean
|
|
417
|
+
log?: string
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export interface GenerateChangeSdkInput {
|
|
421
|
+
satoshis: number
|
|
422
|
+
unlockingScriptLength: number
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export interface GenerateChangeSdkOutput {
|
|
426
|
+
satoshis: number
|
|
427
|
+
lockingScriptLength: number
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export interface GenerateChangeSdkChangeInput {
|
|
431
|
+
outputId: number
|
|
432
|
+
satoshis: number
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export interface GenerateChangeSdkChangeOutput {
|
|
436
|
+
satoshis: number
|
|
437
|
+
lockingScriptLength: number
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export interface ValidateGenerateChangeSdkParamsResult {
|
|
441
|
+
hasMaxPossibleOutput?: number
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export function validateGenerateChangeSdkParams(
|
|
445
|
+
params: GenerateChangeSdkParams
|
|
446
|
+
): ValidateGenerateChangeSdkParamsResult {
|
|
447
|
+
if (!Array.isArray(params.fixedInputs)) throw new WERR_INVALID_PARAMETER('fixedInputs', 'an array of objects')
|
|
448
|
+
|
|
449
|
+
const r: ValidateGenerateChangeSdkParamsResult = {}
|
|
450
|
+
|
|
451
|
+
params.fixedInputs.forEach((x, i) => {
|
|
452
|
+
Validation.validateSatoshis(x.satoshis, `fixedInputs[${i}].satoshis`)
|
|
453
|
+
Validation.validateInteger(x.unlockingScriptLength, `fixedInputs[${i}].unlockingScriptLength`, undefined, 0)
|
|
454
|
+
})
|
|
455
|
+
|
|
456
|
+
if (!Array.isArray(params.fixedOutputs)) throw new WERR_INVALID_PARAMETER('fixedOutputs', 'an array of objects')
|
|
457
|
+
params.fixedOutputs.forEach((x, i) => {
|
|
458
|
+
Validation.validateSatoshis(x.satoshis, `fixedOutputs[${i}].satoshis`)
|
|
459
|
+
Validation.validateInteger(x.lockingScriptLength, `fixedOutputs[${i}].lockingScriptLength`, undefined, 0)
|
|
460
|
+
if (x.satoshis === maxPossibleSatoshis) {
|
|
461
|
+
if (r.hasMaxPossibleOutput !== undefined)
|
|
462
|
+
throw new WERR_INVALID_PARAMETER(
|
|
463
|
+
`fixedOutputs[${i}].satoshis`,
|
|
464
|
+
`valid satoshis amount. Only one 'maxPossibleSatoshis' output allowed.`
|
|
465
|
+
)
|
|
466
|
+
r.hasMaxPossibleOutput = i
|
|
467
|
+
}
|
|
468
|
+
})
|
|
469
|
+
|
|
470
|
+
params.feeModel = validateStorageFeeModel(params.feeModel)
|
|
471
|
+
if (params.feeModel.model !== 'sat/kb') throw new WERR_INVALID_PARAMETER('feeModel.model', `'sat/kb'`)
|
|
472
|
+
|
|
473
|
+
Validation.validateOptionalInteger(params.targetNetCount, `targetNetCount`)
|
|
474
|
+
|
|
475
|
+
Validation.validateSatoshis(params.changeFirstSatoshis, 'changeFirstSatoshis', 1)
|
|
476
|
+
Validation.validateSatoshis(params.changeInitialSatoshis, 'changeInitialSatoshis', 1)
|
|
477
|
+
|
|
478
|
+
Validation.validateInteger(params.changeLockingScriptLength, `changeLockingScriptLength`)
|
|
479
|
+
Validation.validateInteger(params.changeUnlockingScriptLength, `changeUnlockingScriptLength`)
|
|
480
|
+
|
|
481
|
+
return r
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export interface GenerateChangeSdkStorageChange extends GenerateChangeSdkChangeInput {
|
|
485
|
+
spendable: boolean
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export function generateChangeSdkMakeStorage(availableChange: GenerateChangeSdkChangeInput[]): {
|
|
489
|
+
allocateChangeInput: (
|
|
490
|
+
targetSatoshis: number,
|
|
491
|
+
exactSatoshis?: number
|
|
492
|
+
) => Promise<GenerateChangeSdkChangeInput | undefined>
|
|
493
|
+
releaseChangeInput: (outputId: number) => Promise<void>
|
|
494
|
+
getLog: () => string
|
|
495
|
+
} {
|
|
496
|
+
const change: GenerateChangeSdkStorageChange[] = availableChange.map(c => ({
|
|
497
|
+
...c,
|
|
498
|
+
spendable: true
|
|
499
|
+
}))
|
|
500
|
+
change.sort((a, b) =>
|
|
501
|
+
a.satoshis < b.satoshis
|
|
502
|
+
? -1
|
|
503
|
+
: a.satoshis > b.satoshis
|
|
504
|
+
? 1
|
|
505
|
+
: a.outputId < b.outputId
|
|
506
|
+
? -1
|
|
507
|
+
: a.outputId > b.outputId
|
|
508
|
+
? 1
|
|
509
|
+
: 0
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
let log = ''
|
|
513
|
+
for (const c of change) log += `change ${c.satoshis} ${c.outputId}\n`
|
|
514
|
+
|
|
515
|
+
const getLog = (): string => log
|
|
516
|
+
|
|
517
|
+
const allocate = (c: GenerateChangeSdkStorageChange) => {
|
|
518
|
+
log += ` -> ${c.satoshis} sats, id ${c.outputId}\n`
|
|
519
|
+
c.spendable = false
|
|
520
|
+
return c
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const allocateChangeInput = async (
|
|
524
|
+
targetSatoshis: number,
|
|
525
|
+
exactSatoshis?: number
|
|
526
|
+
): Promise<GenerateChangeSdkChangeInput | undefined> => {
|
|
527
|
+
log += `allocate target ${targetSatoshis} exact ${exactSatoshis}`
|
|
528
|
+
|
|
529
|
+
if (exactSatoshis !== undefined) {
|
|
530
|
+
const exact = change.find(c => c.spendable && c.satoshis === exactSatoshis)
|
|
531
|
+
if (exact) return allocate(exact)
|
|
532
|
+
}
|
|
533
|
+
const over = change.find(c => c.spendable && c.satoshis >= targetSatoshis)
|
|
534
|
+
if (over) return allocate(over)
|
|
535
|
+
let under: GenerateChangeSdkStorageChange | undefined = undefined
|
|
536
|
+
for (let i = change.length - 1; i >= 0; i--) {
|
|
537
|
+
if (change[i].spendable) {
|
|
538
|
+
under = change[i]
|
|
539
|
+
break
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (under) return allocate(under)
|
|
543
|
+
log += `\n`
|
|
544
|
+
return undefined
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const releaseChangeInput = async (outputId: number): Promise<void> => {
|
|
548
|
+
log += `release id ${outputId}\n`
|
|
549
|
+
const c = change.find(x => x.outputId === outputId)
|
|
550
|
+
if (!c) throw new WERR_INTERNAL(`unknown outputId ${outputId}`)
|
|
551
|
+
if (c.spendable) throw new WERR_INTERNAL(`release of spendable outputId ${outputId}`)
|
|
552
|
+
c.spendable = true
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return { allocateChangeInput, releaseChangeInput, getLog }
|
|
556
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { Beef } from '@bsv/sdk'
|
|
2
|
+
import { StorageProvider } from '../StorageProvider'
|
|
3
|
+
import { ProvenOrRawTx, StorageGetBeefOptions } from '../../sdk/WalletStorage.interfaces'
|
|
4
|
+
import { EntityProvenTx } from '../schema/entities/EntityProvenTx'
|
|
5
|
+
import { WERR_INVALID_MERKLE_ROOT, WERR_INVALID_OPERATION, WERR_INVALID_PARAMETER } from '../../sdk/WERR_errors'
|
|
6
|
+
import { asBsvSdkTx, verifyTruthy } from '../../utility/utilityHelpers'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Creates a `Beef` to support the validity of a transaction identified by its `txid`.
|
|
10
|
+
*
|
|
11
|
+
* `storage` is used to retrieve proven transactions and their merkle paths,
|
|
12
|
+
* or proven_tx_req record with beef of external inputs (internal inputs meged by recursion).
|
|
13
|
+
* Otherwise external services are used.
|
|
14
|
+
*
|
|
15
|
+
* `options.maxRecursionDepth` can be set to prevent overly deep chained dependencies. Will throw ERR_EXTSVS_ENVELOPE_DEPTH if exceeded.
|
|
16
|
+
*
|
|
17
|
+
* If `trustSelf` is true, a partial `Beef` will be returned where transactions known by `storage` to
|
|
18
|
+
* be valid by verified proof are represented solely by 'txid'.
|
|
19
|
+
*
|
|
20
|
+
* If `knownTxids` is defined, any 'txid' required by the `Beef` that appears in the array is represented solely as a 'known' txid.
|
|
21
|
+
*
|
|
22
|
+
* @param storage the chain on which txid exists.
|
|
23
|
+
* @param txid the transaction hash for which an envelope is requested.
|
|
24
|
+
* @param options
|
|
25
|
+
*/
|
|
26
|
+
export async function getBeefForTransaction(
|
|
27
|
+
storage: StorageProvider,
|
|
28
|
+
txid: string,
|
|
29
|
+
options: StorageGetBeefOptions
|
|
30
|
+
): Promise<Beef> {
|
|
31
|
+
const beef =
|
|
32
|
+
// deserialize mergeToBeef if it is an array
|
|
33
|
+
Array.isArray(options.mergeToBeef)
|
|
34
|
+
? Beef.fromBinary(options.mergeToBeef)
|
|
35
|
+
: // otherwise if undefined create a new Beef
|
|
36
|
+
options.mergeToBeef || new Beef()
|
|
37
|
+
|
|
38
|
+
await mergeBeefForTransactionRecurse(beef, storage, txid, options, 0)
|
|
39
|
+
|
|
40
|
+
return beef
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @returns rawTx if txid known to network, if merkle proof available then also proven result is valid.
|
|
45
|
+
*/
|
|
46
|
+
async function getProvenOrRawTxFromServices(
|
|
47
|
+
storage: StorageProvider,
|
|
48
|
+
txid: string,
|
|
49
|
+
options: StorageGetBeefOptions
|
|
50
|
+
): Promise<ProvenOrRawTx> {
|
|
51
|
+
const services = storage.getServices()
|
|
52
|
+
const por = await EntityProvenTx.fromTxid(txid, await storage.getServices())
|
|
53
|
+
if (por.proven && !options.ignoreStorage && !options.ignoreNewProven) {
|
|
54
|
+
por.proven.provenTxId = await storage.insertProvenTx(por.proven.toApi())
|
|
55
|
+
}
|
|
56
|
+
return { proven: por.proven?.toApi(), rawTx: por.rawTx }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function mergeBeefForTransactionRecurse(
|
|
60
|
+
beef: Beef,
|
|
61
|
+
storage: StorageProvider,
|
|
62
|
+
txid: string,
|
|
63
|
+
options: StorageGetBeefOptions,
|
|
64
|
+
recursionDepth: number
|
|
65
|
+
): Promise<Beef> {
|
|
66
|
+
const maxDepth = storage.maxRecursionDepth
|
|
67
|
+
if (maxDepth && maxDepth <= recursionDepth)
|
|
68
|
+
throw new WERR_INVALID_OPERATION(`Maximum BEEF depth exceeded. Limit is ${storage.maxRecursionDepth}`)
|
|
69
|
+
|
|
70
|
+
if (options.knownTxids && options.knownTxids.indexOf(txid) > -1) {
|
|
71
|
+
// This txid is one of the txids the caller claims to already know are valid...
|
|
72
|
+
beef.mergeTxidOnly(txid)
|
|
73
|
+
return beef
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!options.ignoreStorage) {
|
|
77
|
+
// if we can use storage, ask storage if it has the txid
|
|
78
|
+
const requiredLevels = options.minProofLevel === undefined ? undefined : options.minProofLevel + recursionDepth
|
|
79
|
+
const knownBeef = await storage.getValidBeefForTxid(
|
|
80
|
+
txid,
|
|
81
|
+
beef,
|
|
82
|
+
options.trustSelf,
|
|
83
|
+
options.knownTxids,
|
|
84
|
+
undefined,
|
|
85
|
+
requiredLevels
|
|
86
|
+
)
|
|
87
|
+
if (knownBeef) return knownBeef
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (options.ignoreServices)
|
|
91
|
+
throw new WERR_INVALID_PARAMETER(`txid ${txid}`, `valid transaction on chain ${storage.chain}`)
|
|
92
|
+
|
|
93
|
+
// if storage doesn't know about txid, use services
|
|
94
|
+
// to find it and if it has a proof, remember it.
|
|
95
|
+
const r = await getProvenOrRawTxFromServices(storage, txid, options)
|
|
96
|
+
|
|
97
|
+
if (r.proven && options.minProofLevel !== undefined && options.minProofLevel > recursionDepth) {
|
|
98
|
+
// ignore proof at this recursion depth
|
|
99
|
+
r.proven = undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (r.proven) {
|
|
103
|
+
// storage has proven this txid,
|
|
104
|
+
// merge both the raw transaction and its merkle path
|
|
105
|
+
const mp = new EntityProvenTx(r.proven).getMerklePath()
|
|
106
|
+
if (options.chainTracker) {
|
|
107
|
+
const root = mp.computeRoot()
|
|
108
|
+
const isValid = await options.chainTracker.isValidRootForHeight(root, r.proven.height)
|
|
109
|
+
if (!isValid) {
|
|
110
|
+
if (!options.skipInvalidProofs) {
|
|
111
|
+
throw new WERR_INVALID_MERKLE_ROOT(r.proven.blockHash, r.proven.height, root, txid)
|
|
112
|
+
}
|
|
113
|
+
// ignore this currently invalid proof and try to recurse deeper
|
|
114
|
+
r.proven = undefined
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (r.proven) {
|
|
118
|
+
beef.mergeRawTx(r.proven.rawTx)
|
|
119
|
+
beef.mergeBump(mp)
|
|
120
|
+
return beef
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (!r.rawTx) throw new WERR_INVALID_PARAMETER(`txid ${txid}`, `valid transaction on chain ${storage.chain}`)
|
|
125
|
+
|
|
126
|
+
// merge the raw transaction and recurse over its inputs.
|
|
127
|
+
beef.mergeRawTx(r.rawTx!)
|
|
128
|
+
// recurse inputs
|
|
129
|
+
const tx = asBsvSdkTx(r.rawTx!)
|
|
130
|
+
for (const input of tx.inputs) {
|
|
131
|
+
const inputTxid = verifyTruthy(input.sourceTXID)
|
|
132
|
+
if (!beef.findTxid(inputTxid)) {
|
|
133
|
+
// Only if the txid is not already in the list of beef transactions.
|
|
134
|
+
await mergeBeefForTransactionRecurse(beef, storage, inputTxid, options, recursionDepth + 1)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return beef
|
|
139
|
+
}
|