Compare commits

..
397 Commits
Author SHA1 Message Date
Chris Troutner 2f1d6995a6 Merge pull request #289 from Permissionless-Software-Foundation/ct-unstable
Updating README
2026-02-17 13:25:01 -07:00
Chris Troutner 462885e97b Updating README 2026-02-17 13:21:48 -07:00
Chris Troutner 24774a706e fix(README): updating README 2026-02-17 13:19:18 -07:00
Chris Troutner d5f7e6aa7f Merge pull request #288 from Permissionless-Software-Foundation/ct-unstable
Error handling improvements
2026-02-04 12:58:12 -07:00
Chris Troutner 04e3346086 fix(error handling): Improved error handling. Thowing errors, not objects 2026-02-04 12:54:40 -07:00
Chris Troutner cb2a90fc93 Adding testing script 2026-02-04 09:44:19 -07:00
Chris Troutner 66c2d3ab22 Merge pull request #287 from Permissionless-Software-Foundation/ct-unstable
Updating dependencies for node.js v22
2026-01-16 10:47:45 -07:00
Chris Troutner 89d13fe241 fix(nodejs v22): Adjusting tests. Node.js v22 2x slower on encryption 2026-01-16 10:44:15 -07:00
Chris Troutner ad0b1b5ddb Updating to nodejs v22 2026-01-16 08:48:40 -07:00
Chris Troutner ae30b89d68 Merge pull request #286 from Permissionless-Software-Foundation/ct-unstable
fix(psf-slp-indexer): Adding block height forecast to unconfirmed non…
2026-01-15 16:27:21 -07:00
Chris Troutner 2e88d26ff2 fix(psf-slp-indexer): Adding block height forecast to unconfirmed non-SLP TXs 2026-01-15 16:23:47 -07:00
Chris Troutner b1745d37e0 Merge pull request #285 from Permissionless-Software-Foundation/ct-unstable
fix(x402): Updating x402-bch-axios with faster payment
2025-12-31 15:33:06 -07:00
Chris Troutner 9733c07e04 fix(x402): Updating x402-bch-axios with faster payment 2025-12-31 15:28:44 -07:00
Chris Troutner 430f5f015e Merge pull request #284 from Permissionless-Software-Foundation/ct-unstable
fix(x402): Changing x402 default payment to 25,000 sats, so tx fee is 1%
2025-12-30 13:37:19 -07:00
Chris Troutner 9e76b34d05 fix(x402): Changing x402 default payment to 25,000 sats, so tx fee is 1% 2025-12-30 13:34:02 -07:00
Chris Troutner 61078b2e91 Merge pull request #283 from Permissionless-Software-Foundation/ct-unstable
fix(x402): Removing leading slash in payment URL
2025-12-29 17:08:41 -07:00
Chris Troutner 82733a7e1a Fixing tests 2025-12-29 17:04:09 -07:00
Chris Troutner 3685ea1541 fix(x402): Removing leading slash in payment URL 2025-12-29 16:43:40 -07:00
Chris Troutner 5f217af3e9 Merge pull request #282 from Permissionless-Software-Foundation/ct-unstable
fix(psf-slp-indexer): Fixing issue with error handling
2025-12-29 13:52:40 -07:00
Chris Troutner e2ca3cfb00 fix(psf-slp-indexer): Fixing issue with error handling 2025-12-29 12:38:30 -07:00
Chris Troutner 690520d72e Merge pull request #281 from Permissionless-Software-Foundation/ct-unstable
fix(x402-bch-axios): Updating to v2.1.1 for better error handling
2025-12-24 15:24:47 -07:00
Chris Troutner 36660f3bc9 Merge branch 'master' into ct-unstable 2025-12-24 15:20:34 -07:00
Chris Troutner 80ee5c8d31 fix(x402-bch-axios): Updating to v2.1.1 for better error handling 2025-12-24 15:19:50 -07:00
Chris Troutner b7e04522ce Merge pull request #280 from Permissionless-Software-Foundation/ct-unstable
fix(x402-bch-axios): Updating from v1.1.2 to v2.1.0
2025-12-24 14:09:54 -07:00
Chris Troutner 19f243428d fix(x402-bch-axios): Updating from v1.1.2 to v2.1.0 2025-12-24 14:06:42 -07:00
Chris Troutner 16079c8d04 Merge pull request #279 from Permissionless-Software-Foundation/ct-unstable
fix(dsproof): Fixing bug with axios instantiation
2025-12-22 09:16:37 -07:00
Chris Troutner 6743ca5fa9 Updating integration test script 2025-12-22 08:58:04 -07:00
Chris Troutner ec046d3ef7 fix(dsproof): Fixing bug with axios instantiation 2025-12-21 15:53:46 -07:00
Chris Troutner 85405d8e70 Merge pull request #278 from Permissionless-Software-Foundation/ct-unstable
fix(x402): Improvements to x402 handling
2025-12-21 14:43:56 -07:00
Chris Troutner 1989b72b2a Updated unit tests 2025-12-21 11:58:23 -07:00
Chris Troutner f1f2bf42d9 linting 2025-12-21 11:46:15 -07:00
Chris Troutner 348a073714 fix(x402): Improvements to x402 handling 2025-12-21 11:45:52 -07:00
Chris Troutner e822b91e2c Merge pull request #277 from Permissionless-Software-Foundation/ct-unstable
fix(sem ver): Ensuring sem ver is owrking
2025-12-21 06:39:18 -07:00
Chris Troutner 29a5173036 fix(sem ver): Ensuring sem ver is owrking 2025-12-21 06:36:01 -07:00
Chris Troutner 0bffff6f9b Merge pull request #276 from Permissionless-Software-Foundation/ct-unstable
Updating integration test scripts
2025-12-19 10:51:23 -07:00
Chris Troutner 8c603d3886 fix(x402): Clarifying x402 server separate from psf-bch-api 2025-12-19 10:45:51 -07:00
Chris Troutner 542e59461f fix(x402): Adding default server for x402 payments 2025-12-19 10:25:07 -07:00
Chris Troutner 0912aadc1a Updating integration test scripts 2025-12-19 10:13:37 -07:00
Chris Troutner 638804de42 tweeking test scripts 2025-12-09 14:16:29 -07:00
Chris Troutner fe33ba3381 Merge pull request #275 from Permissionless-Software-Foundation/ct-unstable
Compatibility upgrades for minimal-slp-wallet
2025-11-26 14:46:59 -08:00
Chris Troutner 6f913cf3ad Merge branch 'master' into ct-unstable 2025-11-26 14:43:18 -08:00
Chris Troutner 4d94ad13ff fix(getUsd): Updating endpoint 2025-11-26 13:59:38 -08:00
Chris Troutner c02080d12a fix(scripts.js): Removing @psf/bitcoincash-ops as a dependency 2025-11-26 13:27:45 -08:00
Chris Troutner cc1809b242 fix(script.js): Trying to satisfy ESM, linter, and minify packager at the same time 2025-11-26 13:15:07 -08:00
Chris Troutner 13a7917d9b fix(rest URL): Normalizing URL so user can submit with or without trailing forward slash 2025-11-26 12:28:12 -08:00
Chris Troutner 1573e0bc4c feat(REST URL): removing default REST URL anti-pattern. Error thrown if URL is not specified at startup 2025-11-26 10:55:34 -08:00
Chris Troutner 3fb5377acd Merge pull request #274 from Permissionless-Software-Foundation/ct-unstable
fix(package.json): Fixing minor issue with package.json that was caus…
2025-11-26 08:37:15 -08:00
Chris Troutner a1ba2ac2f7 Merge branch 'master' into ct-unstable 2025-11-26 08:33:46 -08:00
Chris Troutner 7dc29230da fix(package.json): Fixing minor issue with package.json that was causing warning 2025-11-26 08:30:50 -08:00
Chris Troutner 3b013b6215 Merge pull request #273 from Permissionless-Software-Foundation/ct-unstable
Updating README
2025-11-25 17:17:28 -08:00
Chris Troutner 9129c594dd Merge branch 'v7' into ct-unstable 2025-11-25 17:12:50 -08:00
Chris Troutner 64d99531de fix(README): Updating README 2025-11-25 17:12:32 -08:00
Chris Troutner c9a8c5008e Merge pull request #272 from Permissionless-Software-Foundation/v7
V7
2025-11-25 17:02:01 -08:00
Chris Troutner 7f08789c6a Updating to major version 7 2025-11-25 16:57:48 -08:00
Chris Troutner 63dcddb3ab Fixing unit tests 2025-11-25 16:54:26 -08:00
Chris Troutner c2f150bf81 fix(deps): Updating dependencies 2025-11-25 16:40:38 -08:00
Chris Troutner 889ffcfe1d integration test 2025-11-25 16:36:10 -08:00
Chris Troutner 26a6175889 Got x402 integration tests working 2025-11-25 13:27:13 -08:00
Chris Troutner 07de91afa2 feat(BCHJSWIF): Env var lets user pass WIF private key as env var 2025-11-25 12:09:46 -08:00
Chris Troutner 246da25f91 Added x402 support 2025-11-25 10:59:30 -08:00
Chris Troutner f24d36ccee feat(auth): Added Bearer basic auth, removed other auth patterns 2025-11-25 08:46:18 -08:00
Chris Troutner f80cce96b1 Adjusting package.json scripts 2025-11-25 08:31:11 -08:00
Chris Troutner 1c6939ab43 fix(integration tests): Only supporting BCH, all tests in one directory 2025-11-23 10:30:23 -08:00
Chris Troutner bcb236a66b Fixed last integration test 2025-11-17 10:42:37 -08:00
Chris Troutner b66ff3cb59 fixing unit tests 2025-11-17 10:36:14 -08:00
Chris Troutner 2dad11180b feat(util): Removing util.validateAddress functions 2025-11-17 10:28:27 -08:00
Chris Troutner 22e13ef654 fix(dsproof): Fixed integration test 2025-11-17 10:20:55 -08:00
Chris Troutner 4dabdac792 fix(price): Refactored price and integration tests 2025-11-17 10:13:53 -08:00
Chris Troutner 857b57240e Adding new fulcrum test 2025-11-17 07:45:52 -08:00
Chris Troutner 7b9aba3738 fixed broken fulcrum test 2025-11-17 07:44:30 -08:00
Chris Troutner 2c49af2de3 feat(psf-bch-api): Using psf-bch-api instead of legacy bch-api 2025-11-17 07:37:21 -08:00
Chris Troutner 3c0590ba23 Removing XEC and Testnet integration tests 2025-11-17 07:24:47 -08:00
Chris Troutner b20a034bc9 fix(apidoc): Fixing contrast in api docs 2025-11-16 19:40:15 -08:00
Chris Troutner 12e5143d9a fix(lint): Fixing linting issue 2025-11-16 13:47:24 -08:00
Chris Troutner 8e3fa6dcf1 feat(ESM): Converted code base to ESM format, away from CommonJS 2025-11-16 13:37:04 -08:00
Chris Troutner 76442208a2 Removing unneeded dev dependency 2025-11-16 12:00:44 -08:00
Chris Troutner 2cf8905852 Removing more unnecessary dev dependencies 2025-11-16 11:53:25 -08:00
Chris Troutner d134aff9f4 Removing unneeded dev dependency 2025-11-16 11:47:29 -08:00
Chris Troutner 005b628301 Updating more dependencies 2025-11-16 11:44:45 -08:00
Chris Troutner f3c2168435 Updating more dependencies 2025-11-16 11:38:56 -08:00
Chris Troutner 71b8bb089d Updated more dependencies 2025-11-16 11:34:26 -08:00
Chris Troutner 2333229e54 Upgraded some npm dependencies 2025-11-16 10:55:44 -08:00
Chris Troutner 13c69593b2 Merge pull request #271 from Permissionless-Software-Foundation/ct-unstable
fix(llm): Adding LLM summary of library
2025-11-06 08:54:19 -08:00
Chris Troutner 8316c4eabb fix(llm): Adding LLM summary of library 2025-11-06 08:52:32 -08:00
Chris Troutner 30cf010e80 Merge pull request #270 from Permissionless-Software-Foundation/ct-unstable
fix(axios): Updating axios
2025-10-07 17:42:39 -07:00
Chris Troutner f28eeea5b0 fix(axios): Updating axios 2025-10-07 17:41:12 -07:00
Chris Troutner 9758eb9995 Merge pull request #269 from Permissionless-Software-Foundation/ct-unstable
fix(utxo.get()): Handling corner-case when SLP indexer is not returni…
2025-06-29 14:38:18 -07:00
Chris Troutner 4260a74d91 fix(utxo.get()): Handling corner-case when SLP indexer is not returning data 2025-06-29 14:36:44 -07:00
Chris Troutner 01625abb37 Merge pull request #267 from Permissionless-Software-Foundation/ct-unstable
feat(getPsffppPrice): New endpoint to get PSFFPP pin price
2024-09-03 19:29:59 -07:00
Chris Troutner b34040cd08 feat(getPsffppPrice): New endpoint to get PSFFPP pin price 2024-09-03 19:28:22 -07:00
Chris Troutner 01a4d0f1aa Adding integration-test-pearson.sh to gitignore 2023-06-02 15:03:25 -07:00
Chris Troutner 7c7c6395e1 Merge pull request #265 from Permissionless-Software-Foundation/ct-unstable
fix(nft): Removing NFT parent and child functions from SLPDB that hav…
2023-06-02 06:27:00 -07:00
Chris Troutner 3408a8fd3b fix(nft): Removing NFT parent and child functions from SLPDB that have been replaced with psf-slp-indexer 2023-06-02 06:24:57 -07:00
Chris Troutner 86a1cadfac Merge pull request #264 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Updating documentation
2023-04-09 05:57:08 -07:00
Chris Troutner 7000a83a37 fix(Utxo.get()): Updating documentation 2023-04-09 05:54:22 -07:00
Chris Troutner b331450473 Merge pull request #263 from Permissionless-Software-Foundation/ct-unstable
fix(getPubKey): Debugging errors with getPubKey()
2023-04-08 12:20:32 -07:00
Chris Troutner af7c8ffa6d fix(getPubKey): Debugging errors with getPubKey() 2023-04-08 12:17:40 -07:00
Chris Troutner 2e04548ade Merge pull request #262 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing integration tests that broke with infoUtxo impleme…
2023-04-01 16:38:05 -07:00
Chris Troutner 412fa5e1ce fix(tests): Fixing integration tests that broke with infoUtxo implementation 2023-04-01 16:36:07 -07:00
Chris Troutner a08a4236d6 Merge pull request #261 from Permissionless-Software-Foundation/ct-unstable
feat(Utxo.get()): Creating infoUtxo category for utxos less than 1000…
2023-03-31 13:43:19 -07:00
Chris Troutner e700a22560 feat(Utxo.get()): Creating infoUtxo category for utxos less than 1000 sats 2023-03-31 13:41:37 -07:00
Chris Troutner 4573c63ca3 Merge pull request #260 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Commenting out integration tests that fails due to 429 er…
2023-03-14 06:48:37 -07:00
Chris Troutner bd18e8a755 fix(tests): Commenting out integration tests that fails due to 429 errors 2023-03-14 06:28:50 -07:00
Chris Troutner cf8f48ffe1 Merge pull request #259 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Commenting out integration tests that are commonly failing
2023-03-11 17:28:44 -08:00
Chris Troutner fc96b04a64 fix(tests): Commenting out integration tests that are commonly failing 2023-03-11 17:26:00 -08:00
Chris Troutner 661a759f80 Merge pull request #258 from Permissionless-Software-Foundation/ct-unstable
feat(tx history): Updating to reflect changes in bch-api
2023-02-07 10:03:22 -08:00
Chris Troutner ba915e84cf feat(tx history): Updating to reflect changes in bch-api 2023-02-07 10:01:41 -08:00
Chris Troutner eae7172e3d Merge pull request #257 from Permissionless-Software-Foundation/ct-unstable
fix(getTokenData2()): Adding updateCache input argument
2023-01-26 17:49:48 -08:00
Chris Troutner 6dd2a0590f fix(getTokenData2()): Adding updateCache input argument 2023-01-26 17:48:11 -08:00
Chris Troutner 3152e87b5d Merge pull request #256 from Permissionless-Software-Foundation/electron
fix(bitcoincashjs-lib): Updating to v4.0.3
2023-01-22 09:41:03 -08:00
Chris Troutner 4b66f3841d fix(bitcoincashjs-lib): Updating to v4.0.3 2023-01-22 09:39:03 -08:00
Chris Troutner 9f98a47682 Merge pull request #255 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken integration tests
2023-01-13 07:21:15 -08:00
Chris Troutner 0833e8ca78 fix(tests): Fixing broken integration tests 2023-01-13 07:13:47 -08:00
Chris Troutner e01a18b65e Merge pull request #253 from Permissionless-Software-Foundation/ct-unstable
fix(encryption): Adding documentation for the encryption library
2022-12-14 10:09:43 -08:00
Chris Troutner 055cd7feca fix(encryption): Adding documentation for the encryption library 2022-12-14 10:05:41 -08:00
Chris Troutner 906d9b2094 Merge pull request #252 from Permissionless-Software-Foundation/ct-unstable
fix(utxo.get()): Detecting out-of-sync SLP indexer, protecting tokens
2022-11-01 15:01:44 -07:00
Chris Troutner 9326fd6e59 fix(utxo.get()): Detecting out-of-sync SLP indexer, protecting tokens 2022-11-01 14:58:28 -07:00
Chris Troutner 1d91eed5df Fixing script in package.json 2022-10-16 13:23:16 -07:00
Chris Troutner 62e56c832b Merge pull request #251 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Removing integration tests that trips rate limit
2022-10-13 10:33:55 -07:00
Chris Troutner d5b7e4ab1d fix(tests): Removing integration tests that trips rate limit 2022-10-13 10:31:22 -07:00
Chris Troutner 2137a75fce Merge pull request #250 from Permissionless-Software-Foundation/ct-unstable
fix(getTokenData2): Adding api documentation
2022-10-06 20:43:14 -07:00
Chris Troutner 8966cac210 fix(getTokenData2): Adding api documentation 2022-10-06 20:40:22 -07:00
Chris Troutner 9d32f828bc Cleaning up screen spam 2022-10-06 20:33:36 -07:00
Chris Troutner 91a7106818 Merge pull request #249 from Permissionless-Software-Foundation/ct-unstable
feat(getTokenData2): Adding new endpoint for token icons and other media
2022-10-06 20:27:00 -07:00
Chris Troutner 44e671dfbe fix(price): Removing dead price endpoint tests 2022-10-06 20:24:17 -07:00
Chris Troutner 979fb481de feat(getTokenData2): Adding token media endpoint 2022-10-06 18:30:39 -07:00
Chris Troutner 66253ed5a6 feat(bchjs.Price.current): Removing dead endpoint 2022-10-06 17:58:00 -07:00
Chris Troutner 6ef5ac0f7c feat(getTokenData2): Adding new endpoint for token icons and other media 2022-10-06 17:57:11 -07:00
Chris Troutner 21c322d0df Merge pull request #247 from Permissionless-Software-Foundation/ct-unstable
fix(getTokenData): Adding ability to retrieve tx history
2022-07-12 14:48:22 -07:00
Chris Troutner 1b0e9ef0ff fix(getTokenData): Adding ability to retrieve tx history 2022-07-12 14:24:09 -07:00
Chris Troutner 78776bee93 Merge pull request #246 from Permissionless-Software-Foundation/ct-unstable
fix(deps): npm audit shows now vulns
2022-07-11 07:24:47 -07:00
Chris Troutner a6e3155f37 fix(deps): npm audit shows now vulns 2022-07-11 07:20:20 -07:00
Chris Troutner 47f60bccde Merge pull request #245 from Permissionless-Software-Foundation/ct-unstable
fix(ecash): Adding token support for ecash
2022-07-11 07:11:36 -07:00
Chris Troutner d0a3b27682 fix(ecash): Adding token support for ecash 2022-07-11 07:09:44 -07:00
Chris Troutner 372d1b099d Merge pull request #244 from Permissionless-Software-Foundation/ct-unstable
fix(address): Adding toEtokenAddress() function
2022-07-10 09:50:44 -07:00
Chris Troutner dbfaf9c4ab fix(address): Adding toEtokenAddress() function 2022-07-10 09:47:49 -07:00
Chris Troutner eaa08f74e7 Merge pull request #243 from Permissionless-Software-Foundation/ct-unstable
fix(test): Updating integration test
2022-05-15 07:53:53 -07:00
Chris Troutner 9ac620ee64 fix(test): Updating integration test 2022-05-15 07:50:57 -07:00
Chris Troutner ac0a4b0407 Merge pull request #242 from Permissionless-Software-Foundation/ct-unstable
feat(Utxo.isValid()): can test if a UTXO has been spent
2022-05-10 09:34:37 -07:00
Chris Troutner 686012037f feat(Utxo.isValid()): can test if a UTXO has been spent 2022-05-10 09:30:57 -07:00
Chris Troutner cfb7b9f779 Merge pull request #241 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken UTXO.get() test
2022-05-09 10:35:21 -07:00
Chris Troutner 06e5af4b5d fix(tests): Fixing broken UTXO.get() test 2022-05-09 10:33:06 -07:00
Chris Troutner 249e93a3f4 Merge pull request #240 from Permissionless-Software-Foundation/ct-unstable
fix(test): Updating UTXO integration tests
2022-05-09 10:25:58 -07:00
Chris Troutner 761a2d226c fix(test): Updating UTXO integration tests 2022-05-09 10:24:00 -07:00
Chris Troutner 5e5e636831 Merge pull request #239 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken integration tests for token data
2022-05-09 09:49:02 -07:00
Chris Troutner 2adc2dfebb fix(tests): Fixing broken integration tests for token data 2022-05-09 09:45:28 -07:00
Chris Troutner f9bc44ccb7 Merge pull request #238 from Permissionless-Software-Foundation/ct-unstable
fix(token data): Returning CID rather than content itself
2022-05-07 20:59:55 -07:00
Chris Troutner 298b8f56ff Merge branch 'temp-token-data' into ct-unstable 2022-05-07 20:54:49 -07:00
Chris Troutner 139da8cf7b fix(token data): Returning CID rather than content itself 2022-05-07 20:54:20 -07:00
Chris Troutner 08e03c14d8 Merge pull request #234 from Permissionless-Software-Foundation/dh-psfSlpIndexer
feat(slpindexer): Added bchjs.PsfSlpIndexer.getTokenData()
2022-05-07 20:25:15 -07:00
Chris Troutner 7da010e7af Using config.restURL instead of hard-coded URL 2022-05-07 20:20:30 -07:00
Chris Troutner 7b6eebe7c7 Merge branch 'master' into dh-psfSlpIndexer 2022-05-07 20:05:25 -07:00
Chris Troutner 843f5eacef Merge pull request #237 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Added additional integration tests
2022-05-05 12:08:46 -07:00
Chris Troutner 416e302ca5 fix(Utxo.get()): Added additional integration tests 2022-05-05 12:06:59 -07:00
Chris Troutner 1c66da70b6 Merge pull request #236 from Permissionless-Software-Foundation/ct-unstable
fix(mintNFTGroupOpReturn()): Updating to use UTXOs from psf-slp-indexer
2022-05-05 10:45:59 -07:00
Chris Troutner 59e92adf0b fix(mintNFTGroupOpReturn()): Updating to use UTXOs from psf-slp-indexer 2022-05-05 10:43:40 -07:00
Chris Troutner f369411ccb Merge pull request #235 from Permissionless-Software-Foundation/ct-unstable
Updating Utxo.get()
2022-05-05 10:05:36 -07:00
Chris Troutner 0504cf7b8d fix(Utxo.get()): Adding filtering for Group batons 2022-05-05 10:03:35 -07:00
Chris Troutner 88ae47cade fix(Utxo.get()): Adding prototype NFT filtering 2022-05-04 17:44:53 -07:00
Daniel Gonzalez d144b13500 feat(slpindexer): Added bchjs.PsfSlpIndexer.getTokenData() 2022-05-04 18:29:54 -04:00
Chris Troutner 30d58bc337 Merge pull request #233 from Permissionless-Software-Foundation/ct-unstable
fix(readme): Adding backup information
2022-04-30 19:48:24 -07:00
Chris Troutner 651ae3f6ca fix(readme): Adding backup information 2022-04-30 19:37:30 -07:00
Chris Troutner 04cd90f0f4 Merge pull request #232 from Permissionless-Software-Foundation/ct-unstable
Updating README
2022-04-30 16:09:24 -07:00
Chris Troutner 552ee31b79 Adding QR to readme 2022-04-30 16:07:17 -07:00
Chris Troutner affa9619bb fix(README): Updating README 2022-04-30 16:04:22 -07:00
Chris Troutner 39bff131af fix(generateMintOpReturn): Adding additional input validation 2022-04-24 10:28:46 -07:00
Chris Troutner a84fecfe41 Merge pull request #231 from Permissionless-Software-Foundation/ct-unstable
fix(tokentype1.js): Fixing bug in mint OP_RETURN
2022-04-24 09:57:52 -07:00
Chris Troutner 0736c9f2a1 Merge branch 'master' into ct-unstable 2022-04-24 09:55:00 -07:00
Chris Troutner aa898b31e7 fix(tokentype1.js): Fixing bug in mint OP_RETURN 2022-04-24 09:54:14 -07:00
Chris Troutner 29c3381cc5 Merge pull request #230 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Hydrating mint batons for tokens
2022-04-24 09:16:59 -07:00
Chris Troutner f7ba6bb3ae fix(Utxo.get()): Hydrating mint batons for tokens 2022-04-24 09:15:10 -07:00
Chris Troutner 62056e1ac4 Merge pull request #229 from Permissionless-Software-Foundation/ct-unstable
fix(tokentype1.js): Mint OP_RETURN works with output from psf-slp-ind…
2022-04-24 08:57:56 -07:00
Chris Troutner a60e2fa2da fix(tokentype1.js): Mint OP_RETURN works with output from psf-slp-indexer 2022-04-24 08:51:49 -07:00
Chris Troutner 37fe679800 Merge pull request #228 from Permissionless-Software-Foundation/ct-unstable
fix(util.js): Fixing small bug with Util.validateAddress()
2022-04-23 17:41:04 -07:00
Chris Troutner 4250d841c5 Merge branch 'master' into ct-unstable 2022-04-23 17:36:16 -07:00
Chris Troutner 31079afc35 fix(util.js): Fixing small bug with Util.validateAddress() 2022-04-23 17:18:15 -07:00
Chris Troutner 62b44d5058 Merge pull request #227 from gitter-badger/gitter-badge
Add a Gitter chat badge to README.md
2022-04-05 05:31:20 -07:00
The Gitter Badger 150295cb43 Add Gitter badge 2022-04-05 12:10:09 +00:00
Chris Troutner 5de2f71ea5 Merge pull request #226 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Handling coinbase txs
2022-03-31 07:28:02 -07:00
Chris Troutner 50a1d60229 fix(Transaction.get()): Handling coinbase txs 2022-03-31 07:24:07 -07:00
Chris Troutner f3e25a0338 Merge pull request #225 from Permissionless-Software-Foundation/ct-unstable
fix(npm): Ran npm audit fix. 0 vulns
2022-03-29 16:56:09 -07:00
Chris Troutner 640c582724 fix(npm): Ran npm audit fix. 0 vulns 2022-03-29 16:53:49 -07:00
Chris Troutner b472fa2673 Merge pull request #224 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Fixing typo
2022-03-29 16:22:23 -07:00
Chris Troutner ea83335fd2 fix(Utxo.get()): Moving code to where it needs to be 2022-03-29 16:20:03 -07:00
Chris Troutner 3050819784 fix(Utxo.get()): Fixing typo 2022-03-29 16:15:47 -07:00
Chris Troutner 4ca9b1c00b Merge pull request #223 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Adding property expected by SLP.tokentype1 lib
2022-03-29 16:05:22 -07:00
Chris Troutner bbc1a45a9e fix(Utxo.get()): Adding property expected by SLP.tokentype1 lib 2022-03-29 15:59:55 -07:00
Chris Troutner 469d08e2b1 Merge pull request #222 from Permissionless-Software-Foundation/ct-unstable
Adding API docs for Transaction lib
2022-03-19 07:03:10 -07:00
Chris Troutner dcadad189b fix(getTokenInfo): Adding API documentation 2022-03-19 07:00:27 -07:00
Chris Troutner 02f81ee203 fix(transactoin): Adding API documentation 2022-03-19 06:58:49 -07:00
Chris Troutner 972bf604d1 Merge pull request #221 from Permissionless-Software-Foundation/ct-unstable
feat(slp): Removing more legacy code that dependended on SLPDB
2022-03-19 06:52:11 -07:00
Chris Troutner 82f084edec feat(slp): Removing more legacy code that dependended on SLPDB 2022-03-19 06:49:43 -07:00
Chris Troutner 4764463fc5 Merge pull request #220 from Permissionless-Software-Foundation/ct-unstable
Removing SLPDB endpoints
2022-03-14 15:54:49 -07:00
Chris Troutner 857458db57 feat(slpdb): Removing endpoints that expect SLPDB interface 2022-03-14 15:50:21 -07:00
Chris Troutner 5f8f05d194 Working on removing slpdb endpoints 2022-03-14 15:13:41 -07:00
Chris Troutner e455d9efec fix(dependencies): Ensuring I'm using exact versions. npm audit = 0 vulns 2022-03-14 14:49:28 -07:00
Chris Troutner ad4e05c289 Bumping to v6.0.0 2022-03-14 14:43:52 -07:00
Chris Troutner 0c1eda8e5a Merge pull request #219 from Permissionless-Software-Foundation/ct-unstable
Updates to tests
2022-03-13 19:12:18 -07:00
Chris Troutner f15bc7e454 fix(tests): Deleting unneeded integration tests 2022-03-13 17:25:51 -07:00
Chris Troutner e9113d864e fix(ecash): Removing SLPDB tests 2022-03-13 13:20:09 -07:00
Chris Troutner 277c9ce0fd Merge pull request #217 from Permissionless-Software-Foundation/ct-unstable
feat(ipfs): Removing the ipfs pinning libraries and dependencies
2022-03-10 16:47:43 -08:00
Chris Troutner e0c07d1542 feat(ipfs): Removing the ipfs pinning libraries and dependencies 2022-03-10 16:45:27 -08:00
Chris Troutner 56bc942e87 fix(tests): Fixing broken integration test 2022-03-10 16:38:41 -08:00
Chris Troutner 34b9cefb65 fix(psf-slp-indexer): Switching URL back 2022-03-10 16:37:11 -08:00
Chris Troutner 6a35091eec fix(psf-slp-indexer): Fixing issue with url 2022-03-10 16:24:12 -08:00
Chris Troutner 02e3ff4dcd Merge pull request #216 from Permissionless-Software-Foundation/ct-unstable
fix(psf-slp-indexer): Adding flag for tx history of tokens
2022-02-06 13:26:05 -08:00
Chris Troutner 64f8adea25 fix(psf-slp-indexer): Adding flag for tx history of tokens 2022-02-06 13:23:25 -08:00
Chris Troutner bcf817f5c7 Merge pull request #215 from Permissionless-Software-Foundation/ct-unstable
Fixing integration test
2022-01-31 21:22:25 -08:00
Chris Troutner 541377e548 Fixing integration test 2022-01-31 21:18:08 -08:00
Chris Troutner 84b44b299a Merge pull request #214 from Permissionless-Software-Foundation/ct-unstable
fix(UTXO.get()): Added detection of null-tagged UTXOs
2022-01-31 21:13:50 -08:00
Chris Troutner b6456df1f4 Fixing unit tests 2022-01-31 21:11:11 -08:00
Chris Troutner b1826c04cb fix(UTXO.get()): Added detection of null-tagged UTXOs 2022-01-31 20:57:36 -08:00
Chris Troutner 71755964c8 Merge pull request #213 from Permissionless-Software-Foundation/ct-unstable
Adding Util.chunk100()
2022-01-27 17:39:47 -08:00
Chris Troutner bd1c3b622d feat(chunk100): Adding chunk100 which works just like chunk20 2022-01-27 17:37:20 -08:00
Chris Troutner bdced13230 fix(Electrumx): Added commented code for debugging sorting 2022-01-27 08:52:12 -08:00
Chris Troutner c925bfce46 Merge pull request #212 from Permissionless-Software-Foundation/ct-unstable
Integration Test Maintenance
2022-01-23 07:11:32 -08:00
Chris Troutner 056a47f6b2 fix(integration tests): Got BCHN and ABC integration tests passing 2022-01-23 07:08:41 -08:00
Chris Troutner 51038681d3 fix(transaction.js): Added integrationt test 2022-01-23 06:46:06 -08:00
Chris Troutner 1a2f144baf Merge pull request #211 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Properly handling addresses with no SLP utxos
2022-01-19 14:48:29 -08:00
Chris Troutner 6d70568082 fix(Utxo.get()): Properly handling addresses with no SLP utxos 2022-01-19 14:46:00 -08:00
Chris Troutner 0b1cf57852 fix(integration): Updating integration tests 2022-01-19 12:20:08 -08:00
Chris Troutner 48f7f75c9c Merge pull request #210 from Permissionless-Software-Foundation/ct-unstable
fix(Utxo.get()): Hydrating SLP UTXOs with additional token data
2022-01-19 10:37:45 -08:00
Chris Troutner 0bc96fded5 fix(Utxo.get()): Hydrating SLP UTXOs with additional token data 2022-01-19 10:33:36 -08:00
Chris Troutner 9869211572 Merge pull request #209 from Permissionless-Software-Foundation/ct-unstable
Big changes
2022-01-18 11:53:27 -08:00
Chris Troutner 1056c3724c feat(Utxo.get()): Moving old function to getOld. New get() uses psf-slp-indexer 2022-01-18 11:41:52 -08:00
Chris Troutner 6b838ef9cd feat(Ninsight): Removing Ninsight libraries and tests 2022-01-18 08:45:20 -08:00
Chris Troutner f09573554d fix(PsfSlpIndexer.tx()): Added detection of blacklisted SLP Tokens 2022-01-18 08:32:45 -08:00
Chris Troutner 4a62ae64de Merge pull request #208 from Permissionless-Software-Foundation/ct-unstable
Replacing Transaction.get() with psf-slp-indexer
2022-01-17 19:21:49 -08:00
Chris Troutner 78de9e390e Merge branch 'master' into ct-unstable 2022-01-17 19:16:21 -08:00
Chris Troutner 7d8d0c2d69 Bumping major version to 5.0.0 2022-01-17 19:12:57 -08:00
Chris Troutner 656b0f6809 feat(Transaction.get()): Replacing call with proxy to psf-slp-indexer 2022-01-17 19:12:12 -08:00
Chris Troutner 48808aec14 Merge pull request #207 from Permissionless-Software-Foundation/ct-unstable
fix(slpdb): Removing slpdb from default integration tests
2022-01-17 15:10:26 -08:00
Chris Troutner d50f4a0d50 fix(slpdb): Removing slpdb from default integration tests 2022-01-17 15:07:06 -08:00
Chris Troutner f09f96d365 Merge pull request #206 from Permissionless-Software-Foundation/dh-slp-indexer
feat(indexer): Added PSF SLP Indexer to bch-js
2022-01-17 14:43:23 -08:00
Chris Troutner 7f4745f83c fix(psf-slp-indexer): Added integration tests 2022-01-17 14:39:52 -08:00
Chris Troutner dd5de1424c fix(PsfSlpIndexer.tx): Renaming txId() to tx() 2022-01-17 14:33:49 -08:00
Daniel Gonzalez 30604591bd feat(indexer): Added PSF SLP Indexer to bch-js 2022-01-17 13:37:29 -04:00
Chris Troutner aeb1efe23e Merge pull request #205 from Permissionless-Software-Foundation/ct-unstable
Adding eCash class library
2022-01-10 19:54:31 -08:00
Chris Troutner 6e43f795d7 feat(eCash): Adding eCash class library 2022-01-10 19:51:12 -08:00
Chris Troutner e07a5b9da0 Adding getBlockchainInfo() integration test 2022-01-10 14:48:43 -08:00
Chris Troutner 5ada76eace Merge branch 'master' into ct-unstable 2021-12-20 12:38:18 -08:00
Chris Troutner e605f6f386 Merge pull request #203 from Permissionless-Software-Foundation/temp
Temp
2021-12-15 05:47:56 -08:00
Chris Troutner eb9d0bea2b Merge pull request #202 from mr-zwets/documentation-toHash160
added documentation to function toHash160()
2021-12-15 05:45:17 -08:00
Chris Troutner f185f5de16 Updating integrat test scripts 2021-12-15 05:44:27 -08:00
Chris Troutner d795174916 Merge branch 'master' into documentation-toHash160 2021-12-15 05:39:47 -08:00
mathi 1294bc2149 added documentation toHash160() 2021-12-15 12:08:58 +01:00
Chris Troutner 8117448fd3 Merge pull request #201 from Permissionless-Software-Foundation/ct-unstable
fix(utxo.get()): Throwing error if address===undefined
2021-12-01 14:48:58 -08:00
Chris Troutner c7b51a38ff fix(utxo.get()): Throwing error if address===undefined 2021-12-01 14:45:39 -08:00
Chris Troutner 07d490134a Merge pull request #198 from Permissionless-Software-Foundation/salemkode
Salemkode
2021-11-30 06:38:15 -08:00
Chris Troutner a8a4eb68a6 fix(bchjs.Crypto.sha256): Updating docs 2021-11-30 06:35:19 -08:00
Chris Troutner c05e2f14e2 Merge pull request #197 from salemkode/master
edit docs of bchjs.Crypto.sha256
2021-11-30 06:34:09 -08:00
Salem Mohammed Shamakh 3540d98910 Update docs of bchjs.Crypto.sha256 2021-11-30 08:15:12 +03:00
Chris Troutner d0129c01f3 Merge pull request #196 from Permissionless-Software-Foundation/temp-documentation
Temp documentation
2021-11-13 06:46:59 -08:00
Chris Troutner ad40607e5b Merge pull request #186 from mr-zwets/documentation-fix
small fixes documentation
2021-11-13 06:43:55 -08:00
Chris Troutner a4f0ee6e42 Merge branch 'master' into documentation-fix 2021-11-13 06:42:57 -08:00
Chris Troutner 0b70ea108b Merge pull request #195 from Permissionless-Software-Foundation/temp-documentation
Temp documentation
2021-11-13 06:42:05 -08:00
Chris Troutner cef9a3cf52 Merge pull request #194 from mr-zwets/documentation
clarified some of the documentation
2021-11-13 06:38:04 -08:00
mathi c216f6c075 clarified some of the documentation 2021-11-13 11:37:56 +01:00
Chris Troutner b53f6bcfc6 Merge pull request #193 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Moving util.js integration tests to bchn specific folder
2021-11-10 18:16:45 -08:00
Chris Troutner cbc834cc1a fix(tests): Moving util.js integration tests to bchn specific folder 2021-11-10 17:32:17 -08:00
Chris Troutner 1cb5fe069b Merge pull request #192 from Permissionless-Software-Foundation/ct-unstable
Created Transaction.get3() to help with SLP indexer
2021-11-03 10:21:21 -07:00
Chris Troutner 425e2cbbc1 fix(Transaction.get3()): Created Transaction.get3() 2021-11-03 10:16:38 -07:00
Chris Troutner 9e92f77523 Making progress on Transaction.get3() 2021-11-03 07:53:56 -07:00
Chris Troutner dc85bb4cfe Making progress on Transaction.get3() 2021-11-03 07:53:42 -07:00
Chris Troutner 92960b6957 Merge branch 'master' into ct-unstable 2021-11-02 20:37:07 -07:00
Chris Troutner 6f34ea286a Merge pull request #191 from Permissionless-Software-Foundation/fix-bip32
fix(bip32-util): Moving to @chris.troutner/bip32-util
2021-11-01 06:21:49 -07:00
Chris Troutner 26f39023c4 fix(bip32-util): Moving to @chris.troutner/bip32-util 2021-11-01 06:18:55 -07:00
Chris Troutner 4a3baca72d Messing around with different variations of transaction.get2() 2021-11-01 06:12:14 -07:00
Chris Troutner fe37c3ca43 Merge pull request #190 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get2()): Improvement to vin token inputs
2021-10-31 18:56:09 -07:00
Chris Troutner ff4ffab670 fix(Transaction.get2()): Improvement to vin token inputs 2021-10-31 18:50:47 -07:00
Chris Troutner 400e7b31a8 Merge pull request #189 from Permissionless-Software-Foundation/ct-unstable
Adding Transaction.get2()
2021-10-31 17:02:14 -07:00
Chris Troutner 360fca0475 fix(Transaction.get2()): Added block height to tx data 2021-10-31 16:58:40 -07:00
Chris Troutner ef7056ee7a fix(Transaction.get2()): Added non-validating tx get 2021-10-31 16:29:50 -07:00
Chris Troutner d221077786 Merge pull request #188 from Permissionless-Software-Foundation/ct-unstable
fix(Jenkins): Attempting to fix CI/CD
2021-10-31 14:52:22 -07:00
Chris Troutner 046ab78c6a fix(Jenkins): Attempting to fix CI/CD 2021-10-31 14:44:07 -07:00
Chris Troutner 29e90915e7 Merge pull request #187 from Permissionless-Software-Foundation/ct-unstable
fix(bip-32): Updated bip-32 library to improve vulns
2021-10-31 14:31:52 -07:00
Chris Troutner 3d85dbfb22 Updating depds 2021-10-31 14:26:43 -07:00
Chris Troutner 2c0fa9dfbd Switched to exact dependency versions 2021-10-31 14:22:36 -07:00
Chris Troutner 6ca1d729dc fix(bip-32): Updated bip-32 library to improve vulns 2021-10-31 14:14:13 -07:00
Chris Troutner c095af8a29 Merge branch 'master' into documentation-fix 2021-10-30 09:07:46 -07:00
mathi 89e4ea1635 small fixes documentation 2021-10-30 17:06:46 +02:00
Chris Troutner 85a34a8305 Merge pull request #185 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Adding token ID to tx token inputs
2021-10-28 16:58:56 -07:00
Chris Troutner ef6cfe4409 fix(Transaction.get()): Adding token ID to tx token inputs 2021-10-28 16:56:35 -07:00
Chris Troutner a29d6ed26a Merge pull request #184 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Validating SLP inputs
2021-10-21 21:07:15 -07:00
Chris Troutner fa58a0764c fix(Transaction.get()): Validating SLP inputs 2021-10-21 21:04:11 -07:00
Chris Troutner 2c2fbeaa46 Merge pull request #183 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Fixing another bug in MINT input handling
2021-10-21 20:47:03 -07:00
Chris Troutner 1e4cd5f99e fix(Transaction.get()): Fixing another bug in MINT input handling 2021-10-21 20:44:47 -07:00
Chris Troutner 52c1ebdafe Merge pull request #182 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Fixing bug in previous PR
2021-10-21 19:45:36 -07:00
Chris Troutner 2e56d66f48 fix(Transaction.get()): Fixing bug in previous PR 2021-10-21 19:42:12 -07:00
Chris Troutner 9cf6c7e7a7 Merge pull request #181 from Permissionless-Software-Foundation/ct-unstable
fix(Transaction.get()): Adding support for MINT corner-case
2021-10-21 19:15:08 -07:00
Chris Troutner 43043672c6 linting 2021-10-21 19:12:10 -07:00
Chris Troutner 4f4b2c864d fix(Transaction.get()): Adding support for MINT corner-case 2021-10-21 19:11:55 -07:00
Chris Troutner 951fea8f9b Merge pull request #180 from Permissionless-Software-Foundation/ct-unstable
fix(npm): Ran npm audit fix, to fix vulns
2021-10-16 09:49:50 -07:00
Chris Troutner 6d75dceffb fix(npm): Ran npm audit fix, to fix vulns 2021-10-16 09:46:55 -07:00
Chris Troutner 3a491c7aba Merge pull request #178 from Permissionless-Software-Foundation/ct-unstable
fix(generateGenesisOpReturn): Fixing bug when 0 decimal
2021-10-14 13:08:31 -07:00
Chris Troutner f03c020e4f fix(generateGenesisOpReturn): Fixing bug when 0 decimal 2021-10-14 13:06:15 -07:00
Chris Troutner 4aeb1148e5 Merge pull request #177 from Permissionless-Software-Foundation/review01
added toEcashAddress() & ecashtoCashAddress() for ecash format support
2021-10-04 07:55:41 -07:00
Chris Troutner f03ee13a1e Merge pull request #175 from mr-zwets/master
conversion between bitcoincash: and ecash:
2021-10-04 06:55:48 -07:00
mr-zwets cb98773d6a Merge branch 'Permissionless-Software-Foundation:master' into master 2021-09-23 07:43:07 +02:00
Chris Troutner c593d68ee5 Merge pull request #176 from Permissionless-Software-Foundation/ct-unstable
Improvements to Transaction.get()
2021-09-22 17:36:30 -07:00
Chris Troutner dc7d3a9339 fix(Transaction.get): Using BigNumber for better tokenqty calc 2021-09-22 17:33:27 -07:00
Chris Troutner 6f4cc0f439 fix(Transaction.get): Fixed bug when Genesis TX was input to queried TX 2021-09-22 16:58:14 -07:00
Chris Troutner 7aa0fa865e fix(decodeOpReturn): Fixed api docs 2021-09-22 15:40:23 -07:00
mathi e8b6d7fb36 added toEcashAddress() & ecashtoCashAddress() for ecash format support 2021-09-22 14:38:54 +02:00
Chris Troutner b13ef94ea3 Merge pull request #174 from Permissionless-Software-Foundation/ct-unstable
fix(npm): Ran npm audit fix, 0 vulns
2021-09-20 16:07:18 -07:00
Chris Troutner 912f899f4e fix(npm): Ran npm audit fix, 0 vulns 2021-09-20 16:04:14 -07:00
Chris Troutner 9063d8da0b Merge pull request #173 from Permissionless-Software-Foundation/feat/ecash-price
Feat/ecash price
2021-09-20 16:00:32 -07:00
Chris Troutner f4e2bd96f0 fix(XEC price): Fixing BCHA XEC price feeds 2021-09-20 15:56:42 -07:00
Chris Troutner 1c898a4ad3 Removing ninsight from integration tests 2021-09-20 15:54:54 -07:00
Chris Troutner c4db813f76 Merge pull request #172 from mr-zwets/master
changed getBchaUsd which returns the price for the BCHA denomination, added getXecUsd for the XEC denomination
2021-09-20 15:33:30 -07:00
mathi 38b96b441f changed getBchaUsd so it returns the BCHA denomination, added getXecUsd 2021-09-20 22:13:24 +02:00
Chris Troutner c94f78f510 Merge pull request #170 from Permissionless-Software-Foundation/ct-unstable
fix(minimal-slp-wallet): Fixed code that was breaking minimal-slp-wal…
2021-08-12 09:16:52 -07:00
Chris Troutner 6de2b712ec fix(minimal-slp-wallet): Fixed code that was breaking minimal-slp-wallet build 2021-08-12 09:14:29 -07:00
Chris Troutner 6f681fd7b0 Merge pull request #169 from Permissionless-Software-Foundation/ct-unstable
fix(npm): Ran npm audit fix. 0 vulns
2021-08-09 17:59:43 -07:00
Chris Troutner 9a82effb2b fix(npm): Ran npm audit fix. 0 vulns 2021-08-09 17:41:38 -07:00
Chris Troutner 955a5e428e Merge pull request #168 from Permissionless-Software-Foundation/ct-unstable
fix(getRawTransaction): Fixing integration test
2021-08-09 14:56:52 -07:00
Chris Troutner 44c3bf44f9 fix(getRawTransaction): Fixing integration test 2021-08-09 14:54:49 -07:00
Chris Troutner 31ce84abb0 Merge pull request #167 from Permissionless-Software-Foundation/ct-unstable
fix(waterfallValidateTxid): Skipping validateTxid3() if it throws an error
2021-08-09 10:39:18 -07:00
Chris Troutner 40fa4b6bc1 linting 2021-08-09 10:36:07 -07:00
Chris Troutner 8c5e111d60 fix(waterfallValidateTxid): Skipping validateTxid3() if it throws an error 2021-08-09 10:35:51 -07:00
Chris Troutner 8965dfc57f Merge pull request #166 from Permissionless-Software-Foundation/ct-unstable
fix(apiToken): Changed _this.axiosOptions to this.axiosOptions
2021-08-08 20:06:05 -07:00
Chris Troutner 93904a632f fix(apiToken): Changed _this.axiosOptions to this.axiosOptions 2021-08-08 20:01:38 -07:00
Chris Troutner 851d4c404c fix(rate limits): Fixing more bugs with rate limit handling axios.options 2021-08-08 19:51:01 -07:00
Chris Troutner 44bac45c32 Updating README 2021-08-08 18:42:04 -07:00
Chris Troutner 95ee8054be Merge pull request #165 from Permissionless-Software-Foundation/ct-unstable
fix(Transactions.get()): Adding extra error handling for rate limits
2021-08-08 18:40:43 -07:00
Chris Troutner 547b28cac8 fix(Transactions.get()): Adding extra error handling for rate limits 2021-08-08 18:38:46 -07:00
Chris Troutner 40ba334a41 Merge pull request #163 from Permissionless-Software-Foundation/ct-unstable
fix(validateTxid3): Throwing an error when rate limit encountered.
2021-08-08 18:06:52 -07:00
Chris Troutner ffd8ccaf2b fix(validateTxid3): Throwing an error when rate limit encountered. 2021-08-08 18:04:39 -07:00
Chris Troutner 9a16c0c6d6 Merge pull request #162 from Permissionless-Software-Foundation/ct-unstable
fix(raw-transaction): Fixing JWT token bug
2021-08-07 12:48:00 -07:00
Chris Troutner 52a891fd78 fix(raw-transaction): Fixing JWT token bug 2021-08-07 12:41:24 -07:00
Chris Troutner c09df08429 fix(npm): Ran npm audit fix 2021-07-16 15:56:36 -07:00
Chris Troutner 4dc88c0af3 Merge pull request #160 from Permissionless-Software-Foundation/ct-unstable
fix(transactions): Adding better error messages
2021-07-16 15:20:12 -07:00
Chris Troutner 85caa9556b fix(transactions): Adding better error messages 2021-07-16 15:18:35 -07:00
Chris Troutner bbdc417eb2 Merge pull request #159 from Permissionless-Software-Foundation/ct-unstable
Updating README
2021-07-12 19:57:47 -07:00
Chris Troutner cc3bc002e7 Updating README 2021-07-12 19:52:29 -07:00
Chris Troutner a75e1ab633 Merge pull request #158 from Permissionless-Software-Foundation/ct-unstable
fix(dsproof): Adding documentation
2021-06-22 15:49:17 -07:00
Chris Troutner 8c5f1e2274 fix(dsproof): Adding documentation 2021-06-22 15:47:22 -07:00
Chris Troutner c30e76c942 Merge pull request #157 from Permissionless-Software-Foundation/dh-dsproof
feat(DSProof): Added DSProof to bch-js
2021-06-22 12:28:40 -07:00
Chris Troutner a575621c50 Fixing ABC integration tests 2021-06-22 12:24:29 -07:00
Daniel Gonzalez d3a0c5948a feat(DSProof): Added DSProof to bch-js 2021-06-19 22:40:16 -04:00
Chris Troutner 61bb509195 Merge pull request #156 from Permissionless-Software-Foundation/ct-unstable
fix(raw-transactions): Adding better error handling for rate-limits
2021-06-19 10:43:24 -07:00
Chris Troutner a18e549694 fix(raw-transactions): Adding better error handling for rate-limits 2021-06-19 10:41:49 -07:00
Chris Troutner 7d53f47d8a Merge pull request #155 from Permissionless-Software-Foundation/ct-unstable
fix(error): Adding additional rate limit error handling
2021-06-19 10:09:51 -07:00
Chris Troutner e8e615795d fix(error): Adding additional rate limit error handling 2021-06-19 10:08:28 -07:00
Chris Troutner 5759b096d5 Merge pull request #153 from Permissionless-Software-Foundation/ct-unstable
fix(errors): Throwing rate limit errors as Error objects
2021-06-19 09:44:11 -07:00
Chris Troutner 5b300f68b2 fix(errors): Throwing rate limit errors as Error objects 2021-06-19 09:42:36 -07:00
Chris Troutner 3cce6f9754 Merge pull request #152 from Permissionless-Software-Foundation/ct-unstable
fix(testnet): Fixing testnet integration test
2021-06-18 09:43:06 -07:00
Chris Troutner 3da04d9327 fix(testnet): Fixing testnet integration test 2021-06-18 09:32:07 -07:00
Chris Troutner 79091815a2 Merge pull request #151 from Permissionless-Software-Foundation/ct-unstable
fix(Electrumx): Fixing integration test
2021-06-17 07:19:55 -07:00
Chris Troutner 258144d26d fix(Electrumx): Fixing integration test 2021-06-17 07:16:48 -07:00
Chris Troutner 4c4a45841b Merge pull request #150 from Permissionless-Software-Foundation/ct-unstable
fix(package.json): Using /v5 in npm scripts
2021-06-16 19:17:14 -07:00
Chris Troutner 010afd10a3 Merge branch 'master' into ct-unstable 2021-06-16 19:13:03 -07:00
Chris Troutner 82b4d2ab9e fix(package.json): Using /v5 in npm scripts 2021-06-16 19:12:48 -07:00
Chris Troutner 8eb6a21dc2 Merge pull request #149 from Permissionless-Software-Foundation/ct-unstable
feat(/v5 REST API): Using the new v5 route in bch-api
2021-06-16 19:03:45 -07:00
Chris Troutner 5f2a762d4f feat(/v5 REST API): Using the new v5 route in bch-api 2021-06-16 17:00:08 -07:00
Chris Troutner 24e2c78d03 Merge pull request #148 from Permissionless-Software-Foundation/ct-unstable
fix(testnet): Removing testnet ninsight tests as they rarely pass
2021-05-22 07:58:39 -07:00
Chris Troutner eab02fdbc9 fix(testnet): Removing testnet ninsight tests as they rarely pass 2021-05-22 07:55:02 -07:00
Chris Troutner f7bd9c75db Merge pull request #147 from Permissionless-Software-Foundation/ct-unstable
fix(nft docs): Fixing a typo in docs
2021-05-21 15:54:07 -07:00
Chris Troutner 2a96f3a4f5 fix(nft docs): Fixing a typo in docs 2021-05-21 15:51:43 -07:00
Chris Troutner 3dc4a8ba6f Merge pull request #146 from Permissionless-Software-Foundation/ct-unstable
fix(dependencies): Updating dependencies. 0 npm vulns
2021-05-21 15:39:46 -07:00
Chris Troutner 65916f2c5c fix(dependencies): Updating dependencies. 0 npm vulns 2021-05-21 15:38:02 -07:00
Chris Troutner 18188bfdce Merge pull request #145 from Permissionless-Software-Foundation/nft-group-get-call
Return parent NFT group token information
2021-05-18 12:40:16 -07:00
Stoyan Zhekov 45acc2b0b7 Return parent NFT group token information 2021-05-16 14:22:33 +09:00
Chris Troutner 31913c3fb7 Merge pull request #144 from Permissionless-Software-Foundation/nft-children-get-call
NFT children get call
2021-05-15 08:54:58 -07:00
Stoyan Zhekov 2311643398 Example fixed 2021-05-14 21:58:52 +09:00
Stoyan Zhekov 7501aa0238 Lint fixes 2021-05-14 21:18:08 +09:00
Stoyan Zhekov 92a89a543d List NFT children per group 2021-05-14 21:17:07 +09:00
Chris Troutner cdf8171994 Merge pull request #143 from Permissionless-Software-Foundation/ct-unstable
fix(integration tests): Adding integration tests for bchn with no whi…
2021-05-03 19:18:34 -07:00
Chris Troutner 385baf0afd fix(integration tests): Adding integration tests for bchn with no whitelist SLPDB 2021-05-03 19:15:41 -07:00
Chris Troutner 9a9aababd2 Merge pull request #142 from Permissionless-Software-Foundation/ct-unstable
fix(integration tests): Adding tests for bchn with no whitelist SLPDB
2021-05-03 19:06:14 -07:00
Chris Troutner c228acd28a fix(integration tests): Adding tests for bchn with no whitelist SLPDB 2021-05-03 18:53:41 -07:00
Chris Troutner c1c140bdce Merge pull request #139 from Permissionless-Software-Foundation/dh-getblock
feat(getBlock): Added getBlock endpoint to bch-js
2021-04-07 13:07:05 -07:00
Daniel Gonzalez 54d9b80f26 feat(getBlock): Added getBlock endpoint to bch-js 2021-04-06 21:33:33 -04:00
Chris Troutner 961a190309 Merge pull request #138 from Permissionless-Software-Foundation/ct-unstable
fix(debugging): Removing all the debugging statements
2021-03-26 18:05:04 -08:00
Chris Troutner 2d2a91dfde fix(debugging): Removing all the debugging statements 2021-03-26 18:57:08 -07:00
Chris Troutner fbac18d456 Merge pull request #137 from Permissionless-Software-Foundation/ct-unstable
More connection reset debugging
2021-03-26 17:32:23 -08:00
Chris Troutner 62ae67ceab Logging axios options in decodeOpReturn 2021-03-26 18:29:48 -07:00
Chris Troutner 8e64d854cf fix(hydrateUtxos): Adding debugging info for axiosOptions 2021-03-26 18:26:18 -07:00
Chris Troutner 5fe8e515ff Merge pull request #136 from Permissionless-Software-Foundation/ct-unstable
fix(decodeOpReturn): Adding debugging information
2021-03-26 16:30:50 -08:00
Chris Troutner f11297339b fix(decodeOpReturn): Adding debugging information 2021-03-26 17:27:57 -07:00
Chris Troutner 61d52c8ebe Merge pull request #135 from Permissionless-Software-Foundation/ct-unstable
fix(debugging): Adding additional debugging info to SLP utils
2021-03-26 12:53:35 -08:00
Chris Troutner d89bbe0bf6 fix(debugging): Adding additional debugging info to SLP utils 2021-03-26 13:51:29 -07:00
Chris Troutner 2a1c2500e6 Merge pull request #134 from Permissionless-Software-Foundation/ct-unstable
fix(slp): Adding more verbose error messages for SLP utility functions
2021-03-26 12:16:55 -08:00
Chris Troutner 8879a5170a fix(slp): Adding more verbose error messages for SLP utility functions 2021-03-26 13:11:40 -07:00
Chris Troutner b29cb7c12b Merge pull request #133 from Permissionless-Software-Foundation/ct-unstable
fix(integration tests): slowing down integration tests for the sake o…
2021-03-26 08:28:46 -07:00
Chris Troutner 69fa10d3a6 fix(integration tests): slowing down integration tests for the sake of rate limits 2021-03-26 08:25:39 -07:00
Chris Troutner d16431d165 Merge pull request #132 from Permissionless-Software-Foundation/ct-unstable
Adding Transaction.get()
2021-03-24 07:30:48 -07:00
Chris Troutner faa2972460 fix(Transaction.get()): Added documentation 2021-03-24 07:28:38 -07:00
Chris Troutner 5d3ea2b559 fix(Transaction.get()): Added unit tests 2021-03-24 07:24:08 -07:00
Chris Troutner 40fa6440f4 feat(Transactions.get()): Added tx hydration method 2021-03-23 18:49:27 -07:00
Chris Troutner ce951afddb fix(RawTransactions.getTxData): Adding BCH value to tx inputs 2021-03-23 17:37:00 -07:00
Chris Troutner d2e847d3fb feat(transactions): Created transaction library 2021-03-23 17:11:37 -07:00
Chris Troutner fe697455c0 Merge branch 'master' into ct-unstable 2021-03-09 08:09:01 -08:00
Chris Troutner 25832d52fd fix(raw-transactions): Adding proper axios header for Basic Auth 2021-03-09 08:04:14 -08:00
Chris Troutner 9d0840c2fe Merge pull request #131 from Permissionless-Software-Foundation/ct-unstable
fix(tokenUtxoDetailsWL): Adding usrObj input variable
2021-03-08 17:37:31 -08:00
Chris Troutner 74dc3e7e1d Merge branch 'master' into ct-unstable 2021-03-08 17:33:25 -08:00
Chris Troutner 171786a470 fix(tokenUtxoDetailsWL): Adding usrObj input variable 2021-03-08 17:32:33 -08:00
127 changed files with 32533 additions and 22278 deletions
+2
View File
@@ -4,6 +4,8 @@ wallet-info.txt
wallet.json
integration-test-sweet.sh
integration-test-ss.sh
integration-test-bitfinex.sh
integration-test-pearson.sh
docs/
coverage/
+8
View File
@@ -0,0 +1,8 @@
[
{
"srcDir": "",
"destDir": "",
"files": "**/*.js",
"command": "npm run lint"
}
]
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright 2021 Chris Troutner
Copyright 2022-2026 Permissionless Software Foundation contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+80 -63
View File
@@ -3,26 +3,20 @@
[![Version](https://img.shields.io/npm/v/@psf/bch-js)](https://www.npmjs.com/package/@psf/bch-js)
[![Downloads/week](https://img.shields.io/npm/dw/@psf/bch-js)](https://npmjs.org/package/@psf/bch-js)
[![License](https://img.shields.io/npm/l/@psf/bch-js)](https://github.com/Permissionless-Software-Foundation/bch-js/blob/master/LICENSE.md)
[![js-standard-style](https://img.shields.io/badge/javascript-standard%20code%20style-green.svg?style=flat-square)](https://github.com/feross/standard)
[![js-standard-style](https://img.shields.io/badge/javascript-standard%20code%20style-green.svg?style=flat-square)](https://github.com/feross/standard) [![Join the chat at https://gitter.im/Permissionless-Software-Foundation/bch-js](https://badges.gitter.im/Permissionless-Software-Foundation/bch-js.svg)](https://gitter.im/Permissionless-Software-Foundation/bch-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[bch-js](https://www.npmjs.com/package/@psf/bch-js) is a JavaScript npm library for creating web and mobile apps that can interact with the Bitcoin Cash (BCH) blockchains. It can be used for free, but requires an account on [FullStack.cash](https://fullstack.cash) for increased rate limits. Learn more from [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) about Full Stack Bitcoin Cash development.
### Quick Start Videos:
Here are two YouTube walk-through videos to help you get started:
- [Introduction to bch-js and the bch-js-examples repository](https://youtu.be/GD2i1ZUiyrk)
- [Working with the FullStack.cash JWT token](https://youtu.be/GD2i1ZUiyrk)
[bch-js](https://www.npmjs.com/package/@psf/bch-js) is a JavaScript npm library for creating web and mobile apps that can interact with the Bitcoin Cash (BCH) blockchain. bch-js contains a toolbox of handy tools, and an easy API for talking with [psf-bch-api REST API](https://github.com/Permissionless-Software-Foundation/psf-bch-api). [FullStack.cash](https://fullstack.cash) offers paid cloud access to psf-bch-api. You can run your own infrastructure by following documentation on [CashStack.info](https://cashstack.info).
### Quick Links
- [Code Examples](https://github.com/Permissionless-Software-Foundation/psf-js-examples) using bch-js
- [npm Library](https://www.npmjs.com/package/@psf/bch-js)
- [Documentation](https://bchjs.fullstack.cash/)
- [Examples](https://github.com/Permissionless-Software-Foundation/bch-js-examples)
- [bchn.fullstack.cash](https://bchn.fullstack.cash) - The REST API this library talks to by default.
- [API Reference](https://bchjs.fullstack.cash/)
- [x402-bch.fullstack.cash](https://x402-bch.fullstack.cash) - The REST API this library talks to by default.
- [FullStack.cash](https://fullstack.cash) - cloud-based infrastructure for application developers.
- [FullStack.cash Account](https://fullstack.cash/login) - Get your API key to unlock increased rate limits.
- [Permissionless Software Foundation](https://psfoundation.cash) - The organization that maintains this library.
- [CashStack.info](https://cashstack.info) - bch-js is part of the Cash Stack, a JavaScript framework for writing web 2 and web 3 business applications.
- [Permissionless Software Foundation](https://psfoundation.info) - The organization that maintains this library.
### Quick Notes
@@ -30,77 +24,97 @@ Here are two YouTube walk-through videos to help you get started:
- Instantiate the library in your code:
```
const BCHJS = require("@psf/bch-js")
```javascript
import BCHJS from "@psf/bch-js"
let bchjs = new BCHJS() // Defaults to BCHN network.
// testnet
bchjs = new BCHJS({ restURL: 'https://testnet3.fullstack.cash/v4/' })
```
This library is intended to be paired with
the [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api) REST API, and the infrastructure provided by [FullStack.cash](https://fullstack.cash). The `restURL` property can be changed to work with different Bitcoin Cash networks:
the [psf-bch-api](https://github.com/Permissionless-Software-Foundation/psf-bch-api) REST API, and the infrastructure provided by [FullStack.cash](https://fullstack.cash). The `restURL` property can be changed to work with different Bitcoin Cash networks:
- BCHN Mainnet REST API server: https://bchn.fullstack.cash/v4/
- ABC Mainnet REST API server: https://abc.fullstack.cash/v4/
- Testnet3 REST API server: https://testnet3.fullstack.cash/v4/
- BCHN Mainnet REST API server: https://x402-bch.fullstack.cash/v7/
- Check server status: https://metrics.fullstack.cash
### API Key
## Configuration
The [bch-api](https://github.com/Permissionless-Software-Foundation/bch-api) REST API hosted by [FullStack.cash](https://fullstack.cash) uses JWT tokens to pay for increased
rate limits when interacting with the back end server. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) if you want to understand the system-as-a-whole. The JWT token can be fed to bch-js _implicitly_ or _explicitly_.
bch-js can be configured through constructor options or environment variables. Configuration options passed to the constructor take precedence over environment variables.
- Implicitly: bch-js will detect your JWT token if you set the `BCHJSTOKEN` environment variable.
- Explicitly: You can directly feed in the JWT token with the `apiToken` property when instantiating the library. Here is an example:
### Constructor Options
```
const BCHJS = require("@psf/bch-js")
let bchjs = new BCHJS({
restURL: 'https://bchn.fullstack.cash/v3/',
apiToken: 'eyJhbGciO...' // Your JWT token here.
When instantiating BCHJS, you can pass a configuration object:
```javascript
import BCHJS from "@psf/bch-js"
const bchjs = new BCHJS({
restURL: 'https://x402-bch.fullstack.cash/v5/',
bearerToken: 'your-bearer-token',
wif: 'your-private-key-wif',
paymentAmountSats: 20000,
bchServerURL: 'https://bch.fullstack.cash'
})
```
### Gatsby
### Configuration Options
bch-js is included in this [gatsby-ipfs-template](https://github.com/Permissionless-Software-Foundation/gatsby-ipfs-template) for building uncensorable web apps that can interact with the blockchain. When building a Gatsby (or other front-end app that uses Webpack), you'll need to add these lines to your `gatsby-node.js` file, as per [this issue](https://github.com/gatsbyjs/gatsby/issues/564):
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `restURL` | string | Yes* | - | The REST API server URL for making API calls. Must include trailing slash. *Required unless `RESTURL` environment variable is set. |
| `bearerToken` | string | No | `''` | Bearer token for authentication with the REST API server. |
| `wif` | string | No | `''` | Private key in WIF format. When provided, enables automatic x402 payment handling. |
| `paymentAmountSats` | number | No | `20000` | Default amount of satoshis to send when making x402 payments. |
| `bchServerURL` | string | No | `'https://bch.fullstack.cash'` | BCH server URL used for broadcasting payment transactions to the blockchain. This is separate from `restURL` and is specifically for x402 payment processing. |
```
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
node: {
fs: 'empty'
}
})
}
### Environment Variables
You can also configure bch-js using environment variables:
| Environment Variable | Config Option | Description |
|---------------------|---------------|-------------|
| `RESTURL` | `restURL` | REST API server URL for making API calls. |
| `BCHJSBEARERTOKEN` | `bearerToken` | Bearer token for API authentication. |
| `BCHJSWIF` | `wif` | Private key in WIF format for x402 payments. |
| `BCHJSBCHSERVERURL` | `bchServerURL` | BCH server URL for x402 payment transactions. |
### Understanding restURL vs bchServerURL
These two configuration options serve different purposes:
- **`restURL`**: The REST API server used for all regular API calls (utxo queries, transaction history, etc.). This can be any bch-api compatible server, such as `https://x402-bch.fullstack.cash/v5/` or `https://bch.fullstack.cash/v5/`.
- **`bchServerURL`**: The BCH infrastructure server used specifically for broadcasting x402 payment transactions to the blockchain. This defaults to `https://bch.fullstack.cash` and should typically remain unchanged unless you have specific infrastructure requirements.
**Example Use Case**: Most users will use `https://x402-bch.fullstack.cash/v5/` as their `restURL` to access x402-protected APIs. However, when bch-js needs to make an x402 payment, it uses the `bchServerURL` (default: `https://bch.fullstack.cash`) to broadcast the payment transaction. This ensures payment transactions are sent through a reliable BCH infrastructure endpoint.
```javascript
// Use x402-bch server for API calls, but bch.fullstack.cash for payments
const bchjs = new BCHJS({
restURL: 'https://x402-bch.fullstack.cash/v5/',
wif: 'your-private-key-wif'
// bchServerURL defaults to 'https://bch.fullstack.cash'
})
// Or explicitly set both
const bchjs2 = new BCHJS({
restURL: 'https://x402-bch.fullstack.cash/v5/',
bchServerURL: 'https://bch.fullstack.cash',
wif: 'your-private-key-wif'
})
```
This is because the new IPFS class in bch-js uses the fs library for uploading files, which is not supported by Gatsby.
### Web Apps
We also provide [minimal-slp-wallet-web](https://www.npmjs.com/package/minimal-slp-wallet-web) as a basic Bitcoin Cash wallet with SLP support, for front end projects. bch-js is encapsulated inside the instantiation of the library Class.
[minimal-slp-wallet](https://www.npmjs.com/package/minimal-slp-wallet) is a minimal wallet 'engine' that incorporates bch-js. It's compiled with Browserify for front end apps.
## Features
[This gist](https://gist.github.com/christroutner/6cb9d1b615f3f9363af79723157bc434) shows how to include minimal-slp-wallet into a basic web page without using a framework.
- [ECMAScript 2017 standard JavaScript](https://en.wikipedia.org/wiki/ECMAScript#8th_Edition_-_ECMAScript_2017) used instead of TypeScript. Works
natively with node.js v10 or higher.
- Full SLP tokens support: bch-js has full support for all SLP token functionality, including send, mint, and genesis transactions. It also fully support all aspects of [non-fugible tokans (NFTs)](https://www.youtube.com/watch?v=vvlpYUx6HRs).
- [Semantic Release](https://github.com/semantic-release/semantic-release) for
continuous delivery using semantic versioning.
- [Greenkeeper](https://greenkeeper.io/) automatic dependency management for
automatically maintaining the latest, most secure dependencies.
- [IPFS uploads](https://ipfs.io) of all files and dependencies, to backup
dependencies in case they are ever inaccessible from GitHub or npm.
[bch-wallet-web3-spa](https://github.com/Permissionless-Software-Foundation/bch-wallet-web3-spa) is a React web app template using bch-js and minimal-slp-wallet.
## Documentation:
Full documentation for this library can be found here:
- [Documentation](https://bchjs.fullstack.cash/)
- [API Reference](https://bchjs.fullstack.cash/)
bch-js uses [APIDOC](http://apidocjs.com/) so that documentation and working code
live in the same repository. To generate the documentation:
@@ -113,11 +127,14 @@ live in the same repository. To generate the documentation:
Have questions? Need help? Join our community support
[Telegram channel](https://t.me/bch_js_toolkit)
## IPFS Releases
## Donate
Copies of this repository are also published on [IPFS](https://ipfs.io).
This open source software is developed and maintained by the [Permissionless Software Foundation](https://psfoundation.cash). If this library provides value to you, please consider making a donation to support the PSF developers:
- v4.5.4: QmWv3pxJy3MH8vU5nLUVyzqFxfNKXLQQEnz1rgStNuQijd
<div align="center">
<img src="./img/donation-qr.png" />
<p>bitcoincash:qqsrke9lh257tqen99dkyy2emh4uty0vky9y0z0lsr</p>
</div>
## License
+1 -1
View File
@@ -1,3 +1,3 @@
Examples have been moved to this repository:
Examples have been moved to this repository
https://github.com/Permissionless-Software-Foundation/bch-js-examples
+38
View File
@@ -0,0 +1,38 @@
#!/bin/bash
# Script to improve contrast in auto-generated API documentation
# The code examples in api-doc use grey-on-grey colors that are hard to read.
# This fixes that issue by improving text contrast for better readability.
# Run this script *after* running 'npm run docs'
FILE="./docs/assets/prism.css"
# Check if file exists
if [ ! -f "$FILE" ]; then
echo "Error: $FILE not found. Make sure to run 'npm run docs' first."
exit 1
fi
# Create a backup
#cp "$FILE" "$FILE.bak"
# Improve contrast:
# - Change default text color from #ccc to #e8e8e8 (brighter light gray)
# - Change comment color from #999 to #b5b5b5 (lighter for better visibility)
# - Change punctuation color from #ccc to #e8e8e8 (consistent with text)
# Replace default text color in code[class*="language-"] and pre[class*="language-"]
sed -i 's/color: #ccc;/color: #000000;/g' "$FILE"
# Replace comment color
sed -i 's/color: #999;/color: #b5b5b5;/g' "$FILE"
# Replace punctuation color (already handled by first sed, but explicit for clarity)
# The punctuation token also uses #ccc, so the first sed command handles it
echo "✓ Improved contrast in prism.css:"
echo " - Default text: #ccc → #e8e8e8"
echo " - Comments: #999 → #b5b5b5"
echo " - Punctuation: #ccc → #e8e8e8"
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

+10451
View File
File diff suppressed because it is too large Load Diff
+15714 -11658
View File
File diff suppressed because it is too large Load Diff
+57 -64
View File
@@ -1,29 +1,27 @@
{
"name": "@psf/bch-js",
"version": "4.0.0",
"description": "The FullStack.cash JavaScript library for Bitcoin Cash and SLP Tokens",
"version": "7.0.0",
"type": "module",
"description": "A JavaScript library for working with Bitcoin Cash and SLP Tokens",
"author": "Chris Troutner <chris.troutner@gmail.com>",
"contributors": [
"Gabriel Cardona <gabriel@bitcoin.com>"
"Gabriel Cardona <gabriel@bitcoin.com>",
"Stoyan Zhekov <zh@zhware.net>"
],
"main": "src/bch-js",
"main": "src/bch-js.js",
"scripts": {
"test": "nyc mocha --trace-warnings --unhandled-rejections=strict --timeout 30000 test/unit/",
"test:integration": "npm run test:integration:bchn",
"test:integration:abc": "export RESTURL=https://abc.fullstack.cash/v4/ && export IS_USING_FREE_TIER=true && mocha --timeout 30000 test/integration/ && mocha --timeout 30000 test/integration/chains/abc/",
"test:integration:bchn": "export RESTURL=https://bchn.fullstack.cash/v4/ && export IS_USING_FREE_TIER=true && mocha --timeout 30000 test/integration/ && mocha --timeout 30000 test/integration/chains/bchn/",
"test:integration:testnet": "IS_USING_FREE_TIER=true mocha --timeout 30000 test/integration/chains/testnet/",
"test:integration:local:abc": "export RESTURL=http://localhost:3000/v4/ && mocha --timeout 30000 test/integration && mocha --timeout 30000 test/integration/chains/abc/",
"test:integration:local:bchn": "export RESTURL=http://localhost:3000/v4/ && mocha --timeout 30000 test/integration/ && mocha --timeout 30000 test/integration/chains/bchn/",
"test:integration:local:testnet": "RESTURL=http://localhost:4000/v4/ mocha --timeout 30000 test/integration/chains/testnet",
"test:integration:decatur:bchn": "export RESTURL=http://192.168.0.36:3000/v4/ && mocha --timeout 30000 test/integration/",
"test:temp": "export RESTURL=http://localhost:3000/v4/ && mocha --timeout 30000 -g '#hydrateUtxos' test/integration/",
"test:temp2": "mocha --timeout=30000 -g '#_hydrateUtxo' test/unit/",
"test:temp3": "export RESTURL=https://bchn.fullstack.cash/v4/ && mocha --timeout 30000 -g '#hydrateUtxos' test/integration/",
"test:temp4": "export RESTURL=http://localhost:3000/v4/ && mocha --timeout 30000 -g '#decodeOpReturn' test/integration/",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"coverage:report": "nyc --reporter=html mocha --timeout 25000 test/unit/",
"docs": "./node_modules/.bin/apidoc -i src/ -o docs",
"test": "export RESTURL=http://localhost:5942/v6 && c8 mocha --trace-warnings --unhandled-rejections=strict --timeout 30000 test/unit/",
"test:custom": "export RESTURL=http://localhost:5942/v6 && c8 mocha --trace-warnings --unhandled-rejections=strict --timeout 60000 ${MOCHA_GREP:+--grep $MOCHA_GREP} test/unit/",
"test:integration": "npm run test:integration:local:noauth",
"test:integration:fullstack:free": "export RESTURL=https://bch.fullstack.cash/v6 && mocha --timeout 60000 test/integration/",
"test:integration:fullstack:x402": "export RESTURL=https://x402-bch.fullstack.cash/v6 && export BCHJSWIF=L1eYaneXDDXy8VDig4Arwe8wYHbhtsA5wuQvwsKwhaYeneoZuKG4 && mocha --timeout 120000 test/integration/",
"test:integration:fullstack:auth": "export RESTURL=http://dev.fullstack.cash/v6 && export BCHJSBEARERTOKEN=test01 && mocha --timeout 30000 test/integration/",
"test:integration:local:noauth": "export RESTURL=http://192.168.1.65:5942/v6 && mocha --timeout 30000 test/integration/",
"test:integration:local:auth": "export RESTURL=http://192.168.1.115:5942/v6 && export BCHJSBEARERTOKEN=temp01 && mocha --timeout 30000 test/integration/",
"test:integration:local:x402": "export RESTURL=http://localhost:5942/v6 && export BCHJSWIF=L1eYaneXDDXy8VDig4Arwe8wYHbhtsA5wuQvwsKwhaYeneoZuKG4 && mocha --timeout 1200000 test/integration/",
"test:integration:decatur": "export RESTURL=http://192.168.1.65:5942/v6 && mocha --timeout 30000 test/integration/",
"coverage": "nyc --reporter=html mocha --timeout 25000 test/unit/",
"docs": "./node_modules/.bin/apidoc -i src/ -o docs && ./fix-docs-contrast.sh",
"lint": "standard --env mocha --fix"
},
"license": "MIT",
@@ -33,53 +31,43 @@
"url": "git+https://github.com/Permissionless-Software-Foundation/bch-js.git"
},
"dependencies": {
"@psf/bip21": "^2.0.1",
"@psf/bip32-utils": "^1.0.0",
"@psf/bitcoincash-ops": "^2.0.0",
"@psf/bitcoincashjs-lib": "^4.0.2",
"@psf/coininfo": "^4.0.0",
"@uppy/core": "^1.10.4",
"@uppy/tus": "^1.5.12",
"axios": "^0.21.1",
"bc-bip68": "^1.0.5",
"bchaddrjs-slp": "^0.2.5",
"bigi": "^1.4.2",
"bignumber.js": "^9.0.0",
"bip-schnorr": "^0.3.0",
"bip38": "^2.0.2",
"bip39": "^3.0.2",
"bip66": "^1.1.5",
"bitcoinjs-message": "^2.0.0",
"bs58": "^4.0.1",
"cashaddrjs": "^0.3.3",
"ini": "^1.3.8",
"randombytes": "^2.0.6",
"safe-buffer": "^5.1.2",
"satoshi-bitcoin": "^1.0.4",
"slp-mdm": "0.0.6",
"@chris.troutner/bip32-utils": "1.0.5",
"@psf/bip21": "2.0.1",
"@psf/bitcoincashjs-lib": "4.0.3",
"@psf/coininfo": "4.0.0",
"axios": "1.13.2",
"bc-bip68": "1.0.5",
"bchaddrjs-slp": "0.2.14",
"bigi": "1.4.2",
"bignumber.js": "9.3.1",
"bip-schnorr": "0.6.7",
"bip38": "3.1.1",
"bip39": "3.1.0",
"bip66": "1.1.5",
"bitcoinjs-message": "2.2.0",
"bs58": "4.0.1",
"ecashaddrjs": "1.0.7",
"ini": "6.0.0",
"randombytes": "2.1.0",
"safe-buffer": "5.2.1",
"satoshi-bitcoin": "1.0.5",
"slp-mdm": "0.0.7",
"slp-parser": "0.0.4",
"wif": "^2.0.6"
"wif": "2.0.6",
"x402-bch-axios": "2.2.1"
},
"devDependencies": {
"apidoc": "^0.17.7",
"assert": "^2.0.0",
"chai": "^4.1.2",
"coveralls": "^3.0.2",
"eslint": "5.16.0",
"eslint-config-prettier": "^6.0.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-standard": "^4.0.0",
"husky": "^4.3.6",
"lodash.clonedeep": "^4.5.0",
"mocha": "^6.1.4",
"node-mocks-http": "^1.7.0",
"nyc": "^14.1.0",
"prettier": "^1.18.2",
"semantic-release": "^17.3.9",
"sinon": "^7.3.2",
"standard": "^16.0.3"
"apidoc": "1.2.0",
"assert": "2.1.0",
"c8": "10.1.3",
"chai": "4.1.2",
"husky": "4.3.8",
"lodash.clonedeep": "4.5.0",
"mocha": "11.7.5",
"nyc": "15.1.0",
"semantic-release": "24.2.9",
"sinon": "9.2.2",
"standard": "17.1.2"
},
"apidoc": {
"title": "bch-js",
@@ -89,5 +77,10 @@
"hooks": {
"pre-commit": "npm run lint"
}
},
"standard": {
"parserOptions": {
"ecmaVersion": "latest"
}
}
}
+133 -27
View File
@@ -1,31 +1,20 @@
// const axios = require("axios")
const Bitcoin = require('@psf/bitcoincashjs-lib')
const cashaddr = require('cashaddrjs')
const coininfo = require('@psf/coininfo')
// import axios from "axios"
import Bitcoin from '@psf/bitcoincashjs-lib'
import cashaddr from 'ecashaddrjs'
import coininfo from '@psf/coininfo'
class Address {
constructor (config) {
const tmp = {}
if (!config || !config.restURL) tmp.restURL = 'https://api.bchjs.cash/v4/'
if (!config || !config.restURL) tmp.restURL = 'https://api.bchjs.cash/v5/'
else tmp.restURL = config.restURL
this.restURL = tmp.restURL
this.apiToken = tmp.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
}
@@ -129,6 +118,107 @@ class Address {
return cashAddress.split(':')[1]
}
/**
* @api Address.toEcashAddress() toEcashAddress()
* @apiName toEcashAddress
* @apiGroup Address
* @apiDescription Convert legacy to eCash (XEC) format
*
* @apiExample Example usage:
* // mainnet
* bchjs.Address.toEcashAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2')
* // ecash:qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
* // mainnet no prefix
* bchjs.Address.toEcashAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2', false)
* // qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
*/
toEcashAddress (address, prefix = true) {
const decoded = this._decode(address)
const ecashAddress = cashaddr.encode(
'ecash',
decoded.type,
decoded.hash
)
if (prefix) return ecashAddress
return ecashAddress.split(':')[1]
}
/**
* @api Address.toEtokenAddress() toEtokenAddress()
* @apiName toEtokenAddress
* @apiGroup Address
* @apiDescription Convert legacy to eToken (XEC) format
*
* @apiExample Example usage:
* // mainnet
* bchjs.Address.toEtokenAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2')
* // etoken:qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
* // mainnet no prefix
* bchjs.Address.toEtokenAddress('bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2', false)
* // qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da
*
*/
toEtokenAddress (address, prefix = true) {
const decoded = this._decode(address)
const etokenAddress = cashaddr.encode(
'etoken',
decoded.type,
decoded.hash
)
if (prefix) return etokenAddress
return etokenAddress.split(':')[1]
}
/**
* @api Address.ecashtoCashAddress() ecashtoCashAddress()
* @apiName ecashtoCashAddress
* @apiGroup Address
* @apiDescription Convert legacy to cashAddress format
*
* @apiExample Example usage:
* // mainnet
* bchjs.Address.ecashtoCashAddress('ecash:qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da')
* // bitcoincash:qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2
*
* // mainnet no prefix
* bchjs.Address.ecashtoCashAddress('ecash:qq50d800hgunr8u4trz3uuppspk3mds0dyug2v69da', false)
* // qq50d800hgunr8u4trz3uuppspk3mds0dy9978plt2
*/
ecashtoCashAddress (address, prefix = true) {
const decoded = this._decodeEcashAddress(address)
const cashAddress = cashaddr.encode(
'bitcoincash',
decoded.type,
decoded.hash
)
if (prefix) return cashAddress
return cashAddress.split(':')[1]
}
/**
* @api Address.toHash160() toHash160()
* @apiName toHash160
* @apiGroup Address
* @apiDescription Converts any address format to hash160
*
* @apiExample Example usage:
* // cash address mainnet p2pkh
* bchjs.Address.toHash160("bitcoincash:qptnmya5wkly7xf97wm5ak23yqdsz3l2cyj7k9vyyh")
* // 573d93b475be4f1925f3b74ed951201b0147eac1
*
* // cash address mainnet p2sh
* bchjs.Address.toHash160("bitcoincash:pp7ushdxf5we8mcpaa3wqgsuqt639cu59ur5xu5fug")
* // 7dc85da64d1d93ef01ef62e0221c02f512e3942f
*/
// Converts any address format to hash160
toHash160 (address) {
const legacyAddress = this.toLegacyAddress(address)
@@ -166,7 +256,7 @@ class Address {
* @api Address.hash160ToCash() hash160ToCash()
* @apiName hash160ToCash
* @apiGroup Address
* @apiDescription Convert hash160 to cash address.
* @apiDescription Convert hash160 to cash address. Accepts either hexadecimal or buffer.
*
* @apiExample Example usage:
* bchjs.Address.hash160ToCash("573d93b475be4f1925f3b74ed951201b0147eac1")
@@ -211,28 +301,28 @@ class Address {
return {
prefix: 'bitcoincash',
type: 'P2PKH',
hash: hash,
hash,
format: 'legacy'
}
case info.main.versions.scripthash:
return {
prefix: 'bitcoincash',
type: 'P2SH',
hash: hash,
hash,
format: 'legacy'
}
case info.test.versions.public:
return {
prefix: 'bchtest',
type: 'P2PKH',
hash: hash,
hash,
format: 'legacy'
}
case info.test.versions.scripthash:
return {
prefix: 'bchtest',
type: 'P2SH',
hash: hash,
hash,
format: 'legacy'
}
default:
@@ -271,6 +361,22 @@ class Address {
throw new Error(`Invalid format : ${address}`)
}
_decodeEcashAddress (address) {
if (address.indexOf(':') !== -1) {
const decoded = cashaddr.decode(address)
decoded.format = 'cashaddr'
return decoded
}
try {
const decoded = cashaddr.decode(`ecash:${address}`)
decoded.format = 'cashaddr'
return decoded
} catch (error) {}
throw new Error(`Invalid format : ${address}`)
}
/**
* @api Address.isLegacyAddress() isLegacyAddress()
* @apiName isLegacyAddress
@@ -721,13 +827,13 @@ class Address {
* @apiDescription Detect an addess from an OutputScript..
*
* @apiExample Example usage:
* const script = bchjs.Script.encode([
* const scriptBuffer = bchjs.Script.encode([
* Buffer.from("BOX", "ascii"),
* bchjs.Script.opcodes.OP_CAT,
* Buffer.from("BITBOX", "ascii"),
* bchjs.Script.opcodes.OP_EQUAL
* ]);
* const p2sh_hash160 = bchjs.Crypto.hash160(script);
* const p2sh_hash160 = bchjs.Crypto.hash160(scriptBuffer);
* const scriptPubKey = bchjs.Script.scriptHash.output.encode(p2sh_hash160);
*
* // mainnet address from output script
@@ -754,4 +860,4 @@ class Address {
}
}
module.exports = Address
export default Address
+111 -51
View File
@@ -7,34 +7,44 @@
*/
// bch-api mainnet.
const DEFAULT_REST_API = 'https://api.fullstack.cash/v4/'
// const DEFAULT_REST_API = "http://localhost:3000/v4/"
// const DEFAULT_REST_API = "http://localhost:3000/v5/"
// Global npm libraries
import axios from 'axios'
import {
createSigner,
withPaymentInterceptor,
createPaymentHeader,
selectPaymentRequirements
} from 'x402-bch-axios'
// local deps
const BitcoinCash = require('./bitcoincash')
const Crypto = require('./crypto')
const Util = require('./util')
const Blockchain = require('./blockchain')
const Control = require('./control')
const Generating = require('./generating')
const Mining = require('./mining')
const RawTransactions = require('./raw-transactions')
const Mnemonic = require('./mnemonic')
const Address = require('./address')
const HDNode = require('./hdnode')
const TransactionBuilder = require('./transaction-builder')
const ECPair = require('./ecpair')
const Script = require('./script')
const Price = require('./price')
const Schnorr = require('./schnorr')
const SLP = require('./slp/slp')
const IPFS = require('./ipfs')
const Encryption = require('./encryption')
const Utxo = require('./utxo')
import BitcoinCash from './bitcoincash.js'
import Crypto from './crypto.js'
import Util from './util.js'
import Blockchain from './blockchain.js'
import Control from './control.js'
import Generating from './generating.js'
import Mining from './mining.js'
import RawTransactions from './raw-transactions.js'
import Mnemonic from './mnemonic.js'
import Address from './address.js'
import HDNode from './hdnode.js'
import TransactionBuilder from './transaction-builder.js'
import ECPair from './ecpair.js'
import Script from './script.js'
import Price from './price.js'
import Schnorr from './schnorr.js'
import SLP from './slp/slp.js'
import Encryption from './encryption.js'
import Utxo from './utxo.js'
import Transaction from './transaction.js'
import DSProof from './dsproof.js'
import Ecash from './ecash.js'
// Indexers
const Ninsight = require('./ninsight')
const Electrumx = require('./electrumx')
import Electrumx from './electrumx.js'
import PsfSlpIndexer from './psf-slp-indexer.js'
class BCHJS {
constructor (config) {
@@ -43,44 +53,81 @@ class BCHJS {
this.restURL = config.restURL
} else if (process.env.RESTURL && process.env.RESTURL !== '') {
this.restURL = process.env.RESTURL
} else this.restURL = DEFAULT_REST_API
// Retrieve the apiToken
this.apiToken = '' // default value.
if (config && config.apiToken && config.apiToken !== '') {
this.apiToken = config.apiToken
} else if (process.env.BCHJSTOKEN && process.env.BCHJSTOKEN !== '') {
this.apiToken = process.env.BCHJSTOKEN
} else {
throw new Error(
'REST API URL is required. Provide config.restURL or set the RESTURL environment variable.'
)
}
// Retrieve the Basic Authentication password.
this.authPass = '' // default value.
if (config && config.authPass && config.authPass !== '') {
this.authPass = config.authPass
} else if (process.env.BCHJSAUTHPASS && process.env.BCHJSAUTHPASS !== '') {
this.authPass = process.env.BCHJSAUTHPASS
// Normalize restURL to always have a trailing slash
if (!this.restURL.endsWith('/')) {
this.restURL = this.restURL + '/'
}
// Generate a Basic Authentication token from an auth password
// Retrieve the Bearer token for simple token authentication.
this.bearerToken = '' // default value.
if (config && config.bearerToken && config.bearerToken !== '') {
this.bearerToken = config.bearerToken
} else if (process.env.BCHJSBEARERTOKEN && process.env.BCHJSBEARERTOKEN !== '') {
this.bearerToken = process.env.BCHJSBEARERTOKEN
}
// Generate the authentication token for the authorization header.
this.authToken = ''
if (this.authPass) {
// console.log(`bch-js initialized with authPass: ${this.authPass}`)
// Generate the header for Basic Authentication.
const combined = `fullstackcash:${this.authPass}`
const base64Credential = Buffer.from(combined).toString('base64')
this.authToken = `Basic ${base64Credential}`
if (this.bearerToken) {
this.authToken = `Bearer ${this.bearerToken}`
}
// x402 payment configuration
// If a WIF private key is provided, enable x402 automatic payment handling
this.wif = ''
if (config && config.wif && config.wif !== '') {
this.wif = config.wif
} else if (process.env.BCHJSWIF && process.env.BCHJSWIF !== '') {
this.wif = process.env.BCHJSWIF
}
// Most TXs cost about 250 sats. So we'll set the default to 25000 sats,
// so the mining fee is 1% of the transaction.
this.paymentAmountSats = (config && config.paymentAmountSats) || 25000
// BCH server URL for x402 payments (separate from REST API server)
// This is used when broadcasting payment transactions to the blockchain
if (config && config.bchServerURL && config.bchServerURL !== '') {
this.bchServerURL = config.bchServerURL
} else if (process.env.BCHJSBCHSERVERURL && process.env.BCHJSBCHSERVERURL !== '') {
this.bchServerURL = process.env.BCHJSBCHSERVERURL
} else {
this.bchServerURL = 'https://bch.fullstack.cash/v6'
}
const libConfig = {
restURL: this.restURL,
apiToken: this.apiToken,
authToken: this.authToken
}
// console.log(`apiToken: ${this.apiToken}`)
// If WIF is provided, create an axios instance with x402 payment interceptor
// Otherwise, let sub-modules use their own axios import for backwards compatibility
if (this.wif) {
let axiosInstance = axios.create({
baseURL: this.restURL,
headers: {
authorization: this.authToken
}
})
// Bitcoin.com Ninsight indexer
this.Ninsight = new Ninsight(config)
const signer = createSigner(this.wif, this.paymentAmountSats)
axiosInstance = withPaymentInterceptor(
axiosInstance,
signer,
{
apiType: 'rest-api',
bchServerURL: this.bchServerURL
}
)
libConfig.axios = axiosInstance
}
// ElectrumX indexer
this.Electrumx = new Electrumx(libConfig)
@@ -111,9 +158,22 @@ class BCHJS {
this.SLP = new SLP(libConfig)
this.SLP.HDNode = this.HDNode
this.IPFS = new IPFS()
this.Utxo = new Utxo(libConfig)
this.Transaction = new Transaction(libConfig)
this.DSProof = new DSProof(libConfig)
this.eCash = new Ecash()
this.PsfSlpIndexer = new PsfSlpIndexer(libConfig)
// Expose x402 helper functions for advanced use cases
this.x402 = {
createSigner,
withPaymentInterceptor,
createPaymentHeader,
selectPaymentRequirements
}
}
}
module.exports = BCHJS
export default BCHJS
+10 -11
View File
@@ -1,13 +1,12 @@
const Bitcoin = require('@psf/bitcoincashjs-lib')
const sb = require('satoshi-bitcoin')
const bitcoinMessage = require('bitcoinjs-message')
const bs58 = require('bs58')
const bip21 = require('@psf/bip21')
const coininfo = require('@psf/coininfo')
const bip38 = require('bip38')
const wif = require('wif')
const Buffer = require('safe-buffer').Buffer
import Bitcoin from '@psf/bitcoincashjs-lib'
import sb from 'satoshi-bitcoin'
import bitcoinMessage from 'bitcoinjs-message'
import bs58 from 'bs58'
import bip21 from '@psf/bip21'
import coininfo from '@psf/coininfo'
import bip38 from 'bip38'
import wif from 'wif'
import { Buffer } from 'safe-buffer'
class BitcoinCash {
constructor (address) {
@@ -519,4 +518,4 @@ class BitcoinCash {
}
}
module.exports = BitcoinCash
export default BitcoinCash
+211 -150
View File
@@ -3,33 +3,22 @@
- Add blockhash functionality back into getTxOutProof
*/
const axios = require('axios')
import axios from 'axios'
let _this
// let _this
class Blockchain {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
/**
@@ -52,14 +41,17 @@ class Blockchain {
*/
async getBestBlockHash () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getBestBlockHash`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getBestBlockHash`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -68,8 +60,8 @@ class Blockchain {
* @apiName getBlock
* @apiGroup Blockchain
* @apiDescription
* If verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'. If verbose is true, returns an Object with information about block hash.
*
* If verbose is 0, returns a string that is serialized, hex-encoded data for block 'hash'. If verbose is 1, returns an Object with information about block hash.
* If verbose is 2, returns an Object with information about block hash and information about tx.
* @apiExample Example usage:
* (async () => {
* try {
@@ -80,34 +72,47 @@ class Blockchain {
* }
* })()
*
* // { hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
* // confirmations: 528236,
* // size: 216,
* // height: 1000,
* // version: 1,
* // versionHex: '00000001',
* // merkleroot: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
* // tx:
* // [ 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33' ],
* // time: 1232346882,
* // mediantime: 1232344831,
* // nonce: 2595206198,
* // bits: '1d00ffff',
* // difficulty: 1,
* // chainwork: '000000000000000000000000000000000000000000000000000003e903e903e9',
* // previousblockhash: '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',
* // nextblockhash: '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6' }
* // {
* // hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
* // confirmations: 528236,
* // size: 216,
* // height: 1000,
* // version: 1,
* // versionHex: '00000001',
* // merkleroot: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
* // tx:
* // [ 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33' ],
* // time: 1232346882,
* // mediantime: 1232344831,
* // nonce: 2595206198,
* // bits: '1d00ffff',
* // difficulty: 1,
* // chainwork: '000000000000000000000000000000000000000000000000000003e903e903e9',
* // previousblockhash: '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',
* // nextblockhash: '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6'
* // }
*/
async getBlock (blockhash, verbose = true) {
async getBlock (blockhash, verbosity = 1) {
try {
const response = await axios.get(
`${this.restURL}blockchain/getBlock/${blockhash}?verbose=${verbose}`,
_this.axiosOptions
// Input validation
if (!blockhash || typeof blockhash !== 'string') {
throw new Error('blockhash must be a string')
}
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/getblock`,
{
blockhash,
verbosity
},
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -150,14 +155,17 @@ class Blockchain {
*/
async getBlockchainInfo () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getBlockchainInfo`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getBlockchainInfo`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -181,14 +189,20 @@ class Blockchain {
*/
async getBlockCount () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getBlockCount`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getBlockCount`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
console.log('Error in bch-js/blockchain.js/getBlockCount()')
console.log('blockchain.js restURL: ', this.restURL)
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -214,14 +228,17 @@ class Blockchain {
if (typeof height !== 'string') height = JSON.stringify(height)
try {
const response = await axios.get(
`${this.restURL}blockchain/getBlockHash/${height}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getBlockHash/${height}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -261,9 +278,9 @@ class Blockchain {
try {
// Handle single hash.
if (typeof hash === 'string') {
const response = await axios.get(
`${this.restURL}blockchain/getBlockHeader/${hash}?verbose=${verbose}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getBlockHeader/${hash}?verbose=${verbose}`,
this.axiosOptions
)
return response.data
@@ -271,13 +288,13 @@ class Blockchain {
// Handle array of hashes.
} else if (Array.isArray(hash)) {
// Dev note: must use axios.post for unit test stubbing.
const response = await axios.post(
`${this.restURL}blockchain/getBlockHeader`,
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/getBlockHeader`,
{
hashes: hash,
verbose: verbose
verbose
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -285,8 +302,13 @@ class Blockchain {
throw new Error('Input hash must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
// console.log('Error in bch-js/blockchain.js/getBlockHeader() error: ', error)
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -322,14 +344,17 @@ class Blockchain {
*/
async getChainTips () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getChainTips`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getChainTips`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -354,14 +379,17 @@ class Blockchain {
*/
async getDifficulty () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getDifficulty`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getDifficulty`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -370,14 +398,17 @@ class Blockchain {
if (typeof txid !== 'string') txid = JSON.stringify(txid)
try {
const response = await axios.get(
`${this.restURL}blockchain/getMempoolAncestors/${txid}?verbose=${verbose}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getMempoolAncestors/${txid}?verbose=${verbose}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -385,14 +416,17 @@ class Blockchain {
if (typeof txid !== 'string') txid = JSON.stringify(txid)
try {
const response = await axios.get(
`${this.restURL}blockchain/getMempoolDescendants/${txid}?verbose=${verbose}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getMempoolDescendants/${txid}?verbose=${verbose}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -482,20 +516,20 @@ class Blockchain {
try {
if (typeof txid === 'string') {
const response = await axios.get(
`${this.restURL}blockchain/getMempoolEntry/${txid}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getMempoolEntry/${txid}`,
this.axiosOptions
)
return response.data
} else if (Array.isArray(txid)) {
// Dev note: must use axios.post for unit test stubbing.
const response = await axios.post(
`${this.restURL}blockchain/getMempoolEntry`,
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/getMempoolEntry`,
{
txids: txid
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -503,8 +537,11 @@ class Blockchain {
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -533,14 +570,17 @@ class Blockchain {
*/
async getMempoolInfo () {
try {
const response = await axios.get(
`${this.restURL}blockchain/getMempoolInfo`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getMempoolInfo`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -580,14 +620,17 @@ class Blockchain {
*/
async getRawMempool (verbose = false) {
try {
const response = await axios.get(
`${this.restURL}blockchain/getRawMempool?vebose=${verbose}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/getRawMempool?vebose=${verbose}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -624,24 +667,27 @@ class Blockchain {
}
// Send the request to the REST API.
// const response = await axios.get(
// const response = await this.axios.get(
// `${this.restURL}blockchain/getTxOut/${txid}/${n}?includeMempool=${includeMempool}`,
// _this.axiosOptions
// this.axiosOptions
// )
const response = await axios.post(
`${this.restURL}blockchain/getTxOut`,
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/getTxOut`,
{
txid: txid,
txid,
vout: n,
mempool: includeMempool
},
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -685,21 +731,21 @@ class Blockchain {
try {
// Single txid.
if (typeof txids === 'string') {
const path = `${this.restURL}blockchain/getTxOutProof/${txids}`
const path = `${this.restURL}full-node/blockchain/getTxOutProof/${txids}`
// if (blockhash) path = `${path}?blockhash=${blockhash}`
const response = await axios.get(path, _this.axiosOptions)
const response = await this.axios.get(path, this.axiosOptions)
return response.data
// Array of txids.
} else if (Array.isArray(txids)) {
// Dev note: must use axios.post for unit test stubbing.
const response = await axios.post(
`${this.restURL}blockchain/getTxOutProof`,
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/getTxOutProof`,
{
txids: txids
txids
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -707,47 +753,59 @@ class Blockchain {
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
async preciousBlock (blockhash) {
try {
const response = await axios.get(
`${this.restURL}blockchain/preciousBlock/${blockhash}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/preciousBlock/${blockhash}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
async pruneBlockchain (height) {
try {
const response = await axios.post(
`${this.restURL}blockchain/pruneBlockchain/${height}`,
_this.axiosOptions
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/pruneBlockchain/${height}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
async verifyChain (checklevel = 3, nblocks = 6) {
try {
const response = await axios.get(
`${this.restURL}blockchain/verifyChain?checklevel=${checklevel}&nblocks=${nblocks}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/verifyChain?checklevel=${checklevel}&nblocks=${nblocks}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -792,21 +850,21 @@ class Blockchain {
try {
// Single block
if (typeof proof === 'string') {
const response = await axios.get(
`${this.restURL}blockchain/verifyTxOutProof/${proof}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/blockchain/verifyTxOutProof/${proof}`,
this.axiosOptions
)
return response.data
// Array of hashes.
} else if (Array.isArray(proof)) {
// Dev note: must use axios.post for unit test stubbing.
const response = await axios.post(
`${this.restURL}blockchain/verifyTxOutProof`,
const response = await this.axios.post(
`${this.restURL}full-node/blockchain/verifyTxOutProof`,
{
proofs: proof
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -814,10 +872,13 @@ class Blockchain {
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
}
module.exports = Blockchain
export default Blockchain
+14 -25
View File
@@ -2,33 +2,22 @@
API endpoints for basic control and information of the full node.
*/
const axios = require('axios')
import axios from 'axios'
let _this // Global reference to the instance of this class.
// let _this // Global reference to the instance of this class.
class Control {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
/**
@@ -79,9 +68,9 @@ class Control {
*/
async getNetworkInfo () {
try {
const response = await axios.get(
`${this.restURL}control/getNetworkInfo`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/control/getNetworkInfo`,
this.axiosOptions
)
return response.data
} catch (error) {
@@ -92,9 +81,9 @@ class Control {
async getMemoryInfo () {
try {
const response = await axios.get(
`${this.restURL}control/getMemoryInfo`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/control/getMemoryInfo`,
this.axiosOptions
)
return response.data
} catch (error) {
@@ -115,4 +104,4 @@ class Control {
// }
}
module.exports = Control
export default Control
+6 -6
View File
@@ -1,5 +1,5 @@
const randomBytes = require('randombytes')
const Bitcoin = require('@psf/bitcoincashjs-lib')
import randomBytes from 'randombytes'
import Bitcoin from '@psf/bitcoincashjs-lib'
class Crypto {
/**
@@ -22,7 +22,7 @@ class Crypto {
* // buffer from hex
* let buffer = Buffer.from('03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354', 'hex')
* bchjs.Crypto.sha256(buffer)
* // <Buffer 26 b0 78 0a 68 3a 1e 09 8e 9c b8 cf a1 b0 92 42 28 25 00 97>
* // <Buffer 97 8c 09 dd 46 09 1d 19 22 fa 01 e9 f4 a9 75 b9 1a 37 1f 26 ba 83 99 de 27 d5 38 01 15 21 21 de>
*
* */
// Translate address from any address format into a specific format.
@@ -60,7 +60,7 @@ class Crypto {
* @api Crypto.hash256() hash256()
* @apiName hash256
* @apiGroup Crypto
* @apiDescription Utility for creating double sha256 hash digests of data.
* @apiDescription Utility for creating double sha256 hash digests of buffer encoded data.
*
* @apiExample Example usage:
* // buffer from hex
@@ -86,7 +86,7 @@ class Crypto {
* @api Crypto.hash160() hash160()
* @apiName hash160
* @apiGroup Crypto
* @apiDescription Utility for creating ripemd160(sha256()) hash digests of data.
* @apiDescription Utility for creating ripemd160(sha256()) hash digests of buffer encoded data.
*
* @apiExample Example usage:
* // buffer from hex
@@ -135,4 +135,4 @@ class Crypto {
}
}
module.exports = Crypto
export default Crypto
+74
View File
@@ -0,0 +1,74 @@
import axios from 'axios'
let _this
class DSProof {
constructor (config) {
this.restURL = config.restURL
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
/**
* @api DSProof.getDSProof() getDSProof()
* @apiName getDSProof
* @apiGroup DSProof
* @apiDescription Checks if a transaction generated a double-spend proof.
*
* If a double-spend is attempted, one of the transactions will generate a
* 'double spend proof'. This call can be used to check if a transaction
* generated such a proof.
*
* Merchants should wait 3-5 seconds after receiving notification of a
* transaction before calling this endpoint, to see if the TXID generated a
* proof. If this method returns no data, then the TX can be considered 'safe'
* and not a double spend. If proof data is returned by this method, then
* the transaction generated a proof and can be considered a 'double spend'.
*
* @apiExample Example usage:
* (async () => {
* try {
* const txid = 'ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e'
* const result = await bchjs.DSProof.getDSProof(txid)
* console.log(result);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // returns
* null
*/
async getDSProof (txid) {
try {
if (!txid) {
throw new Error('txid is required')
}
if (txid.length !== 64) {
throw new Error(`txid must be of length 64 (not ${txid.length})`)
}
const response = await _this.axios.get(
`${this.restURL}full-node/dsproof/getdsproof/${txid}`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
}
export default DSProof
+47
View File
@@ -0,0 +1,47 @@
/*
Utility library for converting units with eCash.
*/
class eCash {
/**
* @api eCash.toSatoshi() toSatoshi()
* @apiName toSatoshi
* @apiGroup eCash
* @apiDescription
* Convert XEC units into satoshi units
*
* @apiExample Example usage:
* // convert 10,704.35 XEC to satoshis:
* bchjs.eCash.toSatoshi(10704.35)
* // 1070435
*/
toSatoshi (xec) {
if (typeof xec !== 'number') {
throw new Error('input must be a floating number representing XEC')
}
return Math.floor(xec * 100)
}
/**
* @api eCash.toXec() toXec()
* @apiName toXec
* @apiGroup eCash
* @apiDescription
* Convert satoshi units to XEC units
*
* @apiExample Example usage:
* // convert 1,070,435 satoshis to XEC:
* bchjs.eCash.toSatoshi(1070435)
* // 10704.35
*/
toXec (sats) {
if (typeof sats !== 'number') {
throw new Error('input must be a floating number representing satoshis')
}
return sats / 100
}
}
export default eCash
+3 -3
View File
@@ -1,5 +1,5 @@
const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require('@psf/coininfo')
import Bitcoin from '@psf/bitcoincashjs-lib'
import coininfo from '@psf/coininfo'
class ECPair {
static setAddress (address) {
@@ -166,4 +166,4 @@ class ECPair {
}
}
module.exports = ECPair
export default ECPair
+110 -78
View File
@@ -3,38 +3,29 @@
by FullStack.cash
*/
// Public npm libraries
const axios = require('axios')
import axios from 'axios'
// Local libraries.
const Blockchain = require('./blockchain')
import Blockchain from './blockchain.js'
// const Address = require('./address')
let _this
// let _this
class ElectrumX {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
// Encapsulate dependencies
this.blockchain = new Blockchain(config)
_this = this
}
/**
@@ -44,7 +35,7 @@ class ElectrumX {
* @apiDescription Return a list of uxtos for an address.
*
* @apiExample Example usage:
* (async () => {
* (async () => {
* try {
* let utxo = await bchjs.Electrumx.utxo('bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9');
* console.log(utxo);
@@ -104,22 +95,24 @@ class ElectrumX {
*/
async utxo (address) {
try {
// console.log(`electrumx.js/utxo() restURL: ${this.restURL}`)
// Handle single address.
if (typeof address === 'string') {
const response = await axios.get(
`${this.restURL}electrumx/utxos/${address}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/utxos/${address}`,
this.axiosOptions
)
return response.data
// Handle array of addresses.
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.restURL}electrumx/utxos`,
const response = await this.axios.post(
`${this.restURL}fulcrum/utxos`,
{
addresses: address
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -127,8 +120,11 @@ class ElectrumX {
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -142,7 +138,7 @@ class ElectrumX {
* (async () => {
* try {
* let balance = await bchjs.Electrumx.balance('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf');
* console.log(utxo);
* console.log(balance);
* } catch(error) {
* console.error(error)
* }
@@ -159,7 +155,7 @@ class ElectrumX {
* (async () => {
* try {
* let balance = await bchjs.Electrumx.balance(['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf', 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v']);
* console.log(utxo);
* console.log(balance);
* } catch(error) {
* console.error(error)
* }
@@ -190,20 +186,20 @@ class ElectrumX {
try {
// Handle single address.
if (typeof address === 'string') {
const response = await axios.get(
`${this.restURL}electrumx/balance/${address}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/balance/${address}`,
this.axiosOptions
)
return response.data
// Handle array of addresses.
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.restURL}electrumx/balance`,
const response = await this.axios.post(
`${this.restURL}fulcrum/balance`,
{
addresses: address
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -211,8 +207,11 @@ class ElectrumX {
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -284,25 +283,26 @@ class ElectrumX {
* }
*
*/
async transactions (address, usrObj = null) {
async transactions (address, usrObj = null, allTxs = false) {
try {
// Handle single address.
if (typeof address === 'string') {
const response = await axios.get(
`${this.restURL}electrumx/transactions/${address}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/transactions/${address}/${allTxs}`,
this.axiosOptions
)
return response.data
// Handle array of addresses.
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.restURL}electrumx/transactions`,
const response = await this.axios.post(
`${this.restURL}fulcrum/transactions`,
{
addresses: address,
usrObj // pass user data when making an internal call.
usrObj, // pass user data when making an internal call.
allTxs
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -310,8 +310,12 @@ class ElectrumX {
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
// console.log('Error in transactions(): ', error)
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -381,20 +385,20 @@ class ElectrumX {
try {
// Handle single address.
if (typeof address === 'string') {
const response = await axios.get(
`${this.restURL}electrumx/unconfirmed/${address}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/unconfirmed/${address}`,
this.axiosOptions
)
return response.data
// Handle array of addresses.
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.restURL}electrumx/unconfirmed`,
const response = await this.axios.post(
`${this.restURL}fulcrum/unconfirmed`,
{
addresses: address
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -402,8 +406,11 @@ class ElectrumX {
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -450,17 +457,21 @@ class ElectrumX {
*/
async blockHeader (height, count = 1) {
try {
const response = await axios.get(
`${this.restURL}electrumx/block/headers/${height}?count=${count}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/block/headers/${height}?count=${count}`,
this.axiosOptions
)
return response.data
} catch (error) {
// console.log("error: ", error)
if (error.response && error.response.data) {
if (error.response && error.response.data) {
throw new Error(error.response.data.error)
} else throw error.response.data
const errorData = error.response.data
if (errorData.error) {
throw new Error(errorData.error)
} else {
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
}
} else {
throw error
}
@@ -541,18 +552,18 @@ class ElectrumX {
try {
// Handle single transaction.
if (typeof txid === 'string') {
const response = await axios.get(
`${this.restURL}electrumx/tx/data/${txid}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}fulcrum/tx/data/${txid}`,
this.axiosOptions
)
return response.data
} else if (Array.isArray(txid)) {
const response = await axios.post(
`${this.restURL}electrumx/tx/data`,
const response = await this.axios.post(
`${this.restURL}fulcrum/tx/data`,
{
txids: txid
},
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -560,8 +571,11 @@ class ElectrumX {
throw new Error('Input txId must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -589,10 +603,10 @@ class ElectrumX {
async broadcast (txHex) {
try {
if (typeof txHex === 'string') {
const response = await axios.post(
`${this.restURL}electrumx/tx/broadcast`,
const response = await this.axios.post(
`${this.restURL}fulcrum/tx/broadcast`,
{ txHex },
_this.axiosOptions
this.axiosOptions
)
return response.data
@@ -600,8 +614,11 @@ class ElectrumX {
throw new Error('Input txHex must be a string.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.response && error.response.data) {
const errorData = error.response.data
const errorMessage = typeof errorData === 'string' ? errorData : (errorData.error || errorData.message || JSON.stringify(errorData))
throw new Error(errorMessage)
} else throw error
}
}
@@ -638,13 +655,24 @@ class ElectrumX {
// Sort confirmed Transactions by the block height
sortConfTxs (txs, sortingOrder = 'DESCENDING') {
try {
// console.log(`sortConfTxs txs: ${JSON.stringify(txs, null, 2)}`)
// Filter out unconfirmed transactions, with a height of 0 or less.
txs = txs.filter(elem => elem.height > 0)
if (sortingOrder === 'DESCENDING') {
return txs.sort((a, b) => b.height - a.height)
// console.log('Sorting in descending order')
return txs.sort((a, b) => {
// console.log(`descending b.height: ${b.height}, a.height: ${a.height}`)
return b.height - a.height
})
}
return txs.sort((a, b) => a.height - b.height)
// console.log('Sorting in ascending order')
return txs.sort((a, b) => {
// console.log(`ascending b.height: ${b.height}, a.height: ${a.height}`)
return a.height - b.height
})
} catch (err) {
console.log('Error in util.js/sortConfTxs()')
throw err
@@ -685,6 +713,8 @@ class ElectrumX {
// Substitute zero-conf txs with the current block-height + 1
async sortAllTxs (txs, sortingOrder = 'DESCENDING') {
try {
// console.log(`sortingOrder: ${sortingOrder}`)
// Calculate the height of the next block
const nextBlock = (await this.blockchain.getBlockCount()) + 1
@@ -700,9 +730,11 @@ class ElectrumX {
return this.sortConfTxs(modifiedTxs, sortingOrder)
} catch (err) {
console.log('Error in util.js/sort0ConfTxs')
console.log('electrumx.js restURL: ', this.restURL)
throw err
}
}
}
module.exports = ElectrumX
export default ElectrumX
+34 -19
View File
@@ -2,44 +2,59 @@
This library contains useful functions that deal with encryption.
*/
const axios = require('axios')
import axios from 'axios'
let _this
class Encryption {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.axios = axios
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
_this = this
}
/**
* @api encryption.getPubKey() getPubKey()
* @apiName Encryption getPubKey()
* @apiGroup Encryption
* @apiDescription Get the public key for an address
* Given an address, the command will search the blockchain for a public
* key associated with that address. The address needs to have made at least
* one spend transaction, in order for its public key to be retrievable.
*
* @apiExample Example usage:
*(async () => {
* try {
* const addr = 'bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d'
* const pubkey = await bchjs.encryption.getPubKey(addr);
* console.log(pubkey);
* } catch(err) {
* console.error(err)
* }
*})()
*
*/
// Search the blockchain for a public key associated with a BCH address.
async getPubKey (addr) {
try {
if (!addr || typeof addr !== 'string') { throw new Error('Input must be a valid Bitcoin Cash address.') }
if (!addr || typeof addr !== 'string') {
throw new Error('Input must be a valid Bitcoin Cash address.')
}
const response = await _this.axios.get(
`${this.restURL}encryption/publickey/${addr}`,
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
@@ -49,4 +64,4 @@ class Encryption {
}
}
module.exports = Encryption
export default Encryption
+10 -21
View File
@@ -1,37 +1,26 @@
const axios = require('axios')
import axios from 'axios'
let _this
// let _this
class Generating {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
async generateToAddress (blocks, address, maxtries = 1000000) {
try {
const response = await axios.post(
const response = await this.axios.post(
`${this.restURL}generating/generateToAddress/${blocks}/${address}?maxtries=${maxtries}`,
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
@@ -41,4 +30,4 @@ class Generating {
}
}
module.exports = Generating
export default Generating
+8 -6
View File
@@ -1,7 +1,7 @@
const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require('@psf/coininfo')
const bip32utils = require('@psf/bip32-utils')
const bchaddrjs = require('bchaddrjs-slp')
import Bitcoin from '@psf/bitcoincashjs-lib'
import coininfo from '@psf/coininfo'
import bip32utils from '@chris.troutner/bip32-utils'
import bchaddrjs from 'bchaddrjs-slp'
class HDNode {
constructor (address) {
@@ -34,7 +34,9 @@ class HDNode {
*/
fromSeed (rootSeedBuffer, network = 'mainnet') {
let bitcoincash
if (network === 'bitcoincash' || network === 'mainnet') { bitcoincash = coininfo.bitcoincash.main } else bitcoincash = coininfo.bitcoincash.test
if (network === 'bitcoincash' || network === 'mainnet') {
bitcoincash = coininfo.bitcoincash.main
} else bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
return Bitcoin.HDNode.fromSeedBuffer(
@@ -635,4 +637,4 @@ class HDNode {
}
}
module.exports = HDNode
export default HDNode
-454
View File
@@ -1,454 +0,0 @@
/*
This library interacts with the IPFS REST API at FullStack.cash for uploading
and downloading data from the IPFS network.
*/
const axios = require('axios')
const Uppy = require('@uppy/core')
const Tus = require('@uppy/tus')
const fs = require('fs')
let _this
class IPFS {
constructor (config) {
this.IPFS_API = process.env.IPFS_API
? process.env.IPFS_API
: 'https://ipfs-file-upload.fullstackcash.nl'
// : `http://localhost:5001`
// Default options when calling axios.
this.axiosOptions = {
headers: {
// authorization: `Token ${this.apiToken}`,
timeout: 15000 // Timeout if the server does not respond in time.
}
}
_this = this
_this.axios = axios
_this.fs = fs
// Initialize Uppy
_this.uppy = _this.initUppy()
}
// Initializes Uppy, which is used for file uploads.
initUppy () {
const uppy = Uppy({
allowMultipleUploads: false,
meta: { test: 'avatar' },
debug: false,
restrictions: {
maxFileSize: null,
maxNumberOfFiles: 1,
minNumberOfFiles: 1,
allowedFileTypes: null // type of files allowed to load
}
})
uppy.use(Tus, { endpoint: `${_this.IPFS_API}/uppy-files` })
return uppy
}
/**
* @api IPFS.createFileModelServer() createFileModelServer()
* @apiName createFileModelServer()
* @apiGroup IPFS
* @apiDescription Creates a new model on the server. If successful, will
* return an object with file data. That object contains a BCH address,
* payment amount, and _id required to be able to upload a file.
*
* @apiExample Example usage:
* (async () => {
* try {
* const path = `${__dirname}/ipfs.js`
* let fileData = await bchjs.IPFS.createFileModelServer(path);
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "success": true,
* "hostingCostBCH": 0.00004197,
* "hostingCostUSD": 0.01,
* "file": {
* "payloadLink": "",
* "hasBeenPaid": false,
* "_id": "5ec562319bfacc745e8d8a52",
* "schemaVersion": 1,
* "size": 4458,
* "fileName": "ipfs.js",
* "fileExtension": "js",
* "createdTimestamp": "1589994033.655",
* "hostingCost": 4196,
* "walletIndex": 49,
* "bchAddr": "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c",
* "__v": 0
* }
*/
async createFileModelServer (path) {
try {
// Ensure the file exists.
if (!_this.fs.existsSync(path)) {
throw new Error(`Could not find this file: ${path}`)
}
// Read in the file.
const fileBuf = _this.fs.readFileSync(path)
// console.log(`fileBuf: `, fileBuf)
// console.log(`Buffer length: ${fileBuf.length}`)
// Get the file name from the path.
const splitPath = path.split('/')
const fileName = splitPath[splitPath.length - 1]
// Get the file extension.
const splitExt = fileName.split('.')
const fileExt = splitExt[splitExt.length - 1]
const fileObj = {
schemaVersion: 1,
size: fileBuf.length,
fileName: fileName,
fileExtension: fileExt
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
const fileData = await _this.axios.post(`${this.IPFS_API}/files`, {
file: fileObj
})
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)
return fileData.data
} catch (err) {
console.error('Error in createFileModel()')
throw err
}
}
/**
* @api IPFS.uploadFileServer() uploadFileServer()
* @apiName uploadFile()
* @apiGroup IPFS
* @apiDescription Upload a file to the FullStack.cash IPFS server. If
* successful, it will return an object with an ID, a BCH address, and an
* amount of BCH to pay.
*
* @apiExample Example usage:
* (async () => {
* try {
* const path = `${__dirname}/ipfs.js`
* let fileData = await bchjs.IPFS.uploadFileServer(path, "5ec562319bfacc745e8d8a52");
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "schemaVersion": 1,
* "size": 2374,
* "fileId": "5ec562319bfacc745e8d8a52",
* "fileName": "ipfs.js",
* "fileExtension": "js"
* }
*/
async uploadFileServer (path, modelId) {
try {
// Ensure the file exists.
if (!_this.fs.existsSync(path)) {
throw new Error(`Could not find this file: ${path}`)
}
if (!modelId) {
throw new Error(
'Must include a file model ID in order to upload a file.'
)
}
// Read in the file.
const fileBuf = _this.fs.readFileSync(path)
// Get the file name from the path.
const splitPath = path.split('/')
const fileName = splitPath[splitPath.length - 1]
// Prepare the upload object. Get a file ID from Uppy.
const id = _this.uppy.addFile({
name: fileName,
data: fileBuf,
source: 'Local',
isRemote: false
})
// console.log(`id: ${JSON.stringify(id, null, 2)}`)
// Add the model ID, required to be allowed to upload the file.
_this.uppy.setFileMeta(id, { fileModelId: modelId })
// Upload the file to the server.
const upData = await _this.uppy.upload()
if (upData.failed.length) {
throw new Error('The file could not be uploaded')
}
if (upData.successful.length) {
delete upData.successful[0].data
// console.log(`upData: ${JSON.stringify(upData, null, 2)}`)
const fileObj = {
schemaVersion: 1,
size: upData.successful[0].progress.bytesTotal,
fileId: upData.successful[0].meta.fileModelId,
fileName: upData.successful[0].name,
fileExtension: upData.successful[0].extension
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
return fileObj
// return true
}
return false
} catch (err) {
console.error('Error in bch-js/src/ipfs.js/upload(): ')
throw err
}
}
/**
* @api IPFS.getStatus() getStatus()
* @apiName getStatus()
* @apiGroup IPFS
* @apiDescription Gets the status of the uploaded file. Will return an object
* that indicates the payment status. If the file is paid, it should contain
* an IPFS hash.
*
* @apiExample Example usage:
* (async () => {
* try {
* const modelId = "5ec7392c2acfe57aa62e945a"
* let fileData = await bchjs.IPFS.getStatus(modelId)
* console.log(fileData)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "hasBeenPaid": true,
* "satCost": 4403,
* "bchAddr": "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk",
* "ipfsHash": "QmRDHPhY5hCNVRMVQvS2H9uty8P1skdwgLaHpUAkEvsjcE",
* "fileId": "5ec7392c2acfe57aa62e945a",
* "fileName": "ipfs-e2e.js"
* }
*/
async getStatus (modelId) {
try {
if (!modelId) throw new Error('Must include a file model ID.')
const fileData = await _this.axios.get(
`${this.IPFS_API}/files/${modelId}`
)
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)
const fileObj = {
hasBeenPaid: fileData.data.file.hasBeenPaid,
satCost: fileData.data.file.hostingCost,
bchAddr: fileData.data.file.bchAddr,
ipfsHash: fileData.data.file.payloadLink,
fileId: fileData.data.file._id,
fileName: fileData.data.file.fileName
}
return fileObj
} catch (err) {
console.error('Error in getStatus()')
throw err
}
}
/**
* @api IPFS.createFileModelWeb() createFileModelWeb()
* @apiName createFileModelWeb()
* @apiGroup IPFS
* @apiDescription Creates a new model on the server. If successful, will
* return an object with file data. That object contains a BCH address,
* payment amount, and _id required to be able to upload a file.
*
* @apiExample Example usage:
* (async () => {
* try {
* const content = ['PSF']
* const name = 'psf.txt' // Content can be Array , ArrayBuffer , Blob
* const options = { type: "text/plain" }
* const file = new File(content,name,options)
* let fileData = await bchjs.IPFS.createFileModelWeb(file);
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "success": true,
* "hostingCostBCH": 0.00004197,
* "hostingCostUSD": 0.01,
* "file": {
* "payloadLink": "",
* "hasBeenPaid": false,
* "_id": "5ec562319bfacc745e8d8a52",
* "schemaVersion": 1,
* "size": 4458,
* "fileName": "ipfs.js",
* "fileExtension": "js",
* "createdTimestamp": "1589994033.655",
* "hostingCost": 4196,
* "walletIndex": 49,
* "bchAddr": "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c",
* "__v": 0
* }
*/
async createFileModelWeb (file) {
try {
if (!file) throw new Error('File is required')
const { name, size } = file
if (!name || typeof name !== 'string') {
throw new Error("File should have the property 'name' of string type")
}
if (!size || typeof size !== 'number') {
throw new Error("File should have the property 'size' of number type")
}
// Get the file extension.
const splitExt = name.split('.')
const fileExt = splitExt[splitExt.length - 1]
const fileObj = {
schemaVersion: 1,
size: size,
fileName: name,
fileExtension: fileExt
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
const fileData = await _this.axios.post(`${this.IPFS_API}/files`, {
file: fileObj
})
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)
return fileData.data
} catch (err) {
console.error('Error in createFileModelWeb()')
throw err
}
}
/**
* @api IPFS.uploadFileWeb() uploadFileWeb()
* @apiName uploadFileWeb()
* @apiGroup IPFS
* @apiDescription Upload a file to the FullStack.cash IPFS server. If
* successful, it will return an object with an ID, a BCH address, and an
* amount of BCH to pay.
*
* @apiExample Example usage:
* (async () => {
* try {
* * const content = ['PSF']
* const name = 'psf.txt' // Content can be Array , ArrayBuffer , Blob
* const options = { type: "text/plain" }
* const file = new File(content,name,options)
* let fileData = await bchjs.IPFS.uploadFile(file, "5ec562319bfacc745e8d8a52");
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "schemaVersion": 1,
* "size": 2374,
* "fileId": "5ec562319bfacc745e8d8a52",
* "fileName": "ipfs.js",
* "fileExtension": "js"
* }
*/
async uploadFileWeb (file, modelId) {
try {
if (!file) throw new Error('File is required')
const { name, type, size } = file
if (!name || typeof name !== 'string') {
throw new Error("File should have the property 'name' of string type")
}
if (!type || typeof type !== 'string') {
throw new Error("File should have the property 'type' of string type")
}
if (!size || typeof size !== 'number') {
throw new Error("File should have the property 'size' of number type")
}
if (!modelId) {
throw new Error(
'Must include a file model ID in order to upload a file.'
)
}
// Prepare the upload object. Get a file ID from Uppy.
const id = _this.uppy.addFile({
name: name,
data: file,
source: 'Local',
isRemote: false
})
// console.log(`id: ${JSON.stringify(id, null, 2)}`)
// Add the model ID, required to be allowed to upload the file.
_this.uppy.setFileMeta(id, { fileModelId: modelId })
// Upload the file to the server.
const upData = await _this.uppy.upload()
if (upData.failed.length) {
throw new Error('The file could not be uploaded')
}
if (upData.successful.length) {
delete upData.successful[0].data
// console.log(`upData: ${JSON.stringify(upData, null, 2)}`)
const fileObj = {
schemaVersion: 1,
size: upData.successful[0].progress.bytesTotal,
fileId: upData.successful[0].meta.fileModelId,
fileName: upData.successful[0].name,
fileExtension: upData.successful[0].extension
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
return fileObj
// return true
}
return false
} catch (err) {
console.error('Error in bch-js/src/ipfs.js/uploadFileWeb(): ')
throw err
}
}
}
module.exports = IPFS
+15 -26
View File
@@ -1,37 +1,26 @@
const axios = require('axios')
import axios from 'axios'
let _this
// let _this
class Mining {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
async getBlockTemplate (templateRequest) {
try {
const response = await axios.get(
const response = await this.axios.get(
`${this.restURL}mining/getBlockTemplate/${templateRequest}`,
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
@@ -42,9 +31,9 @@ class Mining {
async getMiningInfo () {
try {
const response = await axios.get(
const response = await this.axios.get(
`${this.restURL}mining/getMiningInfo`,
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
@@ -55,9 +44,9 @@ class Mining {
async getNetworkHashps (nblocks = 120, height = 1) {
try {
const response = await axios.get(
const response = await this.axios.get(
`${this.restURL}mining/getNetworkHashps?nblocks=${nblocks}&height=${height}`,
_this.axiosOptions
this.axiosOptions
)
return response.data
} catch (error) {
@@ -71,7 +60,7 @@ class Mining {
if (parameters) path = `${path}?parameters=${parameters}`
try {
const response = await axios.post(path, _this.axiosOptions)
const response = await this.axios.post(path, this.axiosOptions)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
@@ -80,4 +69,4 @@ class Mining {
}
}
module.exports = Mining
export default Mining
+8 -11
View File
@@ -1,11 +1,8 @@
/* eslint no-prototype-builtins: "off" */
/* eslint node/no-callback-literal: "off" */
const BIP39 = require('bip39')
const randomBytes = require('randombytes')
const Bitcoin = require('@psf/bitcoincashjs-lib')
const Buffer = require('safe-buffer').Buffer
const wif = require('wif')
import BIP39 from 'bip39'
import randomBytes from 'randombytes'
import Bitcoin from '@psf/bitcoincashjs-lib'
import { Buffer } from 'safe-buffer'
import wif from 'wif'
class Mnemonic {
constructor (address) {
@@ -338,7 +335,7 @@ class Mnemonic {
}
}
module.exports = Mnemonic
export default Mnemonic
// The following code is from: https://raw.githubusercontent.com/iancoleman/bip39/7ff86d4c983f1e8c80b87b31acfd69fcf98c1b82/src/js/levenshtein.js
@@ -356,7 +353,7 @@ const _extend = function (dst) {
const sources = Array.prototype.slice.call(arguments, 1)
for (let i = 0; i < sources.length; ++i) {
const src = sources[i]
for (const p in src) if (src.hasOwnProperty(p)) dst[p] = src[p]
for (const p in src) if (Object.prototype.hasOwnProperty.call(src, p)) dst[p] = src[p]
}
return dst
}
@@ -503,7 +500,7 @@ const Levenshtein = {
try {
options.progress.call(null, (i * 100.0) / str1.length)
} catch (err) {
return cb(`Progress callback: ${err.toString()}`)
return cb(new Error(`Progress callback: ${err.toString()}`))
}
}
-319
View File
@@ -1,319 +0,0 @@
/*
This library interacts with the ninsight REST API endpoints operated by
Bitcoin.com
*/
const axios = require('axios')
let _this
class Ninsight {
constructor (config) {
// this.restURL = config.restURL
// this.apiToken = config.apiToken
// this.ninsightURL = `https://bch-explorer.api.bitcoin.com/v1/`
if (config) {
this.ninsightURL = config.ninsightURL
? config.ninsightURL
: 'https://rest.bitcoin.com/v2'
}
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`,
timeout: 15000
}
}
_this = this
}
/**
* @api Ninsight.utxo() utxo()
* @apiName Ninsight Utxo
* @apiGroup Ninsight
* @apiDescription Return list of uxto for address.
*
* @apiExample Example usage:
* (async () => {
* try {
* let utxo = await bchjs.Ninsight.utxo('bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c');
* console.log(utxo);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // [
* // {
* // "txid": "d31dc2cf66fe4d3d3ae18e1065def58a64920746b1702b52f060e5edeea9883b",
* // "vout": 1,
* // "amount": 0.03608203,
* // "satoshis": 3608203,
* // "height": 585570,
* // "confirmations": 10392
* // },
* // {
* // "txid": "41e9a118765ecf7a1ba4487c0863e23dba343cc5880381a72f0365ac2546c5fa",
* // "vout": 0,
* // "amount": 0.03608203,
* // "satoshis": 3608203,
* // "height": 577125,
* // "confirmations": 18837
* // }
* // ]
*
*/
async utxo (address) {
try {
// Handle single address.
if (typeof address === 'string') {
const response = await axios.post(
`${this.ninsightURL}/address/utxo`,
{
addresses: [address]
},
_this.axiosOptions
)
return response.data
// Handle array of addresses.
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.ninsightURL}/address/utxo`,
{
addresses: address
},
_this.axiosOptions
)
return response.data
}
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
/**
* @api Ninsight.unconfirmed() unconfirmed()
* @apiName Ninsight Unconfirmed Utxo
* @apiGroup Ninsight
* @apiDescription Returns a list of unconfirmed UTXOs for an address.
*
* @apiExample Example usage:
* (async () => {
* try {
* let utxo = await bchjs.Ninsight.unconfirmed('bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c');
* console.log(utxo);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // [
* // {
* // "txid": "d31dc2cf66fe4d3d3ae18e1065def58a64920746b1702b52f060e5edeea9883b",
* // "vout": 1,
* // "amount": 0.03608203,
* // "satoshis": 3608203,
* // "confirmations": 0
* // "ts": 1559670801
* // },
* // {
* // "txid": "41e9a118765ecf7a1ba4487c0863e23dba343cc5880381a72f0365ac2546c5fa",
* // "vout": 0,
* // "amount": 0.03608203,
* // "satoshis": 3608203,
* // "confirmations": 0
* // "ts": 1559670902
* // }
* // ]
*
*/
async unconfirmed (address) {
try {
if (typeof address === 'string') {
const response = await axios.post(
`${this.ninsightURL}/address/unconfirmed`,
{
addresses: [address]
},
_this.axiosOptions
)
return response.data
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.ninsightURL}/address/unconfirmed`,
{
addresses: address
},
_this.axiosOptions
)
return response.data
}
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
/**
* @api Ninsight.transactions() transactions()
* @apiName Ninsight TX History
* @apiGroup Ninsight
* @apiDescription Return transactions history for address.
*
* @apiExample Example usage:
* (async () => {
* try {
* let txs = await bchjs.Ninsight.transactions('bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c');
* console.log(txs);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // [
* // {
* // "pagesTotal": 1,
* // "txs": [
* // {
* // "txid": "ec7bc8349386e3e1939bbdc4f8092fdbdd6a380734e68486b558cd594c451d5b",
* // "version": 2,
* // "locktime": 0,
* // "vin": [
* // {
* // "txid": "4f1fc57c33659628938db740449bf92fb75799e1d5750a4aeef80eb52d6df1e0",
* // "vout": 0,
* // "sequence": 4294967295,
* // "n": 0,
* // ...
* // }
* // ...
* // ]
* // ...
* // }
* // ],
* // "legacyAddress": "1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP",
* // "cashAddress": "bitcoincash:qrvk436u4r0ew2wj0rd9pnxhx4w90p2yfc29ta0d2n",
* // "currentPage": 0
* // }
* // ]
* //
*
*/
async transactions (address) {
try {
if (typeof address === 'string') {
const response = await axios.post(
`${this.ninsightURL}/address/transactions`,
{
addresses: [address]
},
_this.axiosOptions
)
return response.data
} else if (Array.isArray(address)) {
const response = await axios.post(
`${this.ninsightURL}/address/transactions`,
{
addresses: address
},
_this.axiosOptions
)
return response.data
}
throw new Error('Input address must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
/**
* @api Ninsight.txDetails() txDetails()
* @apiName Ninsight TX Details
* @apiGroup Ninsight
* @apiDescription Return transactions details for address(es).
*
* @apiExample Example usage:
* (async () => {
* try {
* let result = await bchjs.Ninsight.txDetails('fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33');
* console.log(result);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // [
* // {
* // "txid": "fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33",
* // "version": 1,
* // "locktime": 0,
* // "vin": [
* // {
* // "sequence": 4294967295,
* // "n": 0
* // }
* // ],
* // "vout": [
* // ...
* // ],
* // "blockhash": "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09",
* // "blockheight": 1000,
* // "confirmations": 659909,
* // "time": 1232346882,
* // "blocktime": 1232346882,
* // "firstSeenTime": null,
* // "valueOut": 50,
* // "size": 135
* // }
* // ]
*
*/
async txDetails (txid) {
try {
if (typeof txid === 'string') {
const response = await axios.post(
`${this.ninsightURL}/transaction/details`,
{
txids: [txid]
},
_this.axiosOptions
)
return response.data
} else if (Array.isArray(txid)) {
const response = await axios.post(
`${this.ninsightURL}/transaction/details`,
{
txids: txid
},
_this.axiosOptions
)
return response.data
}
throw new Error('Transaction ID must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
}
module.exports = Ninsight
+51 -77
View File
@@ -1,47 +1,20 @@
const axios = require('axios')
import axios from 'axios'
let _this
// let _this
class Price {
constructor (config) {
_this = this
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
this.axios = axios
}
// This endpoint is deprecated. Documentation removed.
async current (currency = 'usd') {
try {
const response = await this.axios.get(
`https://index-api.bitcoin.com/api/v0/cash/price/${currency.toLowerCase()}`
)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
return response.data.price
} catch (err) {
if (err.response && err.response.data) throw err.response.data
else throw err
}
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
}
/**
@@ -58,7 +31,7 @@ class Price {
* let current = await bchjs.Price.getUsd();
* console.log(current);
* } catch(err) {
* console.err(err)
* console.error(err)
* }
*})()
*
@@ -67,8 +40,8 @@ class Price {
async getUsd () {
try {
const response = await this.axios.get(
`${this.restURL}price/usd`,
_this.axiosOptions
`${this.restURL}price/bchusd`,
this.axiosOptions
)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
@@ -94,7 +67,7 @@ class Price {
* let current = await bchjs.Price.rates();
* console.log(current);
* } catch(err) {
* console.err(err)
* console.error(err)
* }
*})()
*
@@ -111,7 +84,7 @@ class Price {
try {
const response = await this.axios.get(
`${this.restURL}price/rates`,
_this.axiosOptions
this.axiosOptions
)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
@@ -122,41 +95,6 @@ class Price {
}
}
/**
* @api price.getBchaUsd() getBchaUsd()
* @apiName Price getBchaUsd()
* @apiGroup Price
* @apiDescription Return current price of BCHA in USD.
* This endpoint gets the USD price of BCHA from the Coinex API. The price
* comes from bch-api, so it has a better chance of working in Tor.
*
* @apiExample Example usage:
*(async () => {
* try {
* let current = await bchjs.Price.getBchaUsd();
* console.log(current);
* } catch(err) {
* console.err(err)
* }
*})()
*
* // 18.81
*/
async getBchaUsd () {
try {
const response = await this.axios.get(
`${this.restURL}price/bchausd`,
_this.axiosOptions
)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
return response.data.usd
} catch (err) {
if (err.response && err.response.data) throw err.response.data
else throw err
}
}
/**
* @api price.getBchUsd() getBchUsd()
* @apiName Price getBchUsd()
@@ -171,7 +109,7 @@ class Price {
* let current = await bchjs.Price.getBchUsd();
* console.log(current);
* } catch(err) {
* console.err(err)
* console.error(err)
* }
*})()
*
@@ -181,7 +119,7 @@ class Price {
try {
const response = await this.axios.get(
`${this.restURL}price/bchusd`,
_this.axiosOptions
this.axiosOptions
)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
@@ -191,6 +129,42 @@ class Price {
else throw err
}
}
/**
* @api price.getPsffppPrice() getPsffppPrice()
* @apiName Price getPsffppPrice()
* @apiGroup Price
* @apiDescription Return the cost in PSF tokens to write 1MB of data to the PSFFPP
* Find out more at PSFFPP.com. This is a IPFS pinning service that can pin
* up to 100MB per transaction into its network. The cost is denominated in
* PSF SLP tokens. The endpoint returns the cost to pin 1MB of data to the
* PSFFPP network.
*
* @apiExample Example usage:
*(async () => {
* try {
* let current = await bchjs.Price.getPsffppPrice();
* console.log(current);
* } catch(err) {
* console.error(err)
* }
*})()
*
* // 0.08335233
*/
async getPsffppPrice () {
try {
const response = await this.axios.get(
`${this.restURL}price/psffpp`,
this.axiosOptions
)
return response.data.writePrice
} catch (err) {
if (err.response && err.response.data) throw err.response.data
else throw err
}
}
}
module.exports = Price
export default Price
+549
View File
@@ -0,0 +1,549 @@
/*
This library interacts with the PSF slp indexer REST API endpoints operated
by FullStack.cash
TODO:
- detect TXs from tokens in the blacklist.
*/
// Public npm libraries
import axios from 'axios'
// Local libraries
import RawTransaction from './raw-transactions.js'
import SlpUtils from './slp/utils.js'
import Blockchain from './blockchain.js'
// let _this
class PsfSlpIndexer {
constructor (config = {}) {
this.restURL = config.restURL
this.authToken = config.authToken
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
// Encapsulate dependencies
this.rawTransaction = new RawTransaction(config)
this.slpUtils = new SlpUtils(config)
this.blockchain = new Blockchain(config)
}
/**
* @api PsfSlpIndexer.status() status()
* @apiName Status
* @apiGroup PSF SLP
* @apiDescription Return status from psf slp indexer.
*
* @apiExample Example usage:
* (async () => {
* try {
* let status = await bchjs.PsfSlpIndexer.status()
* console.log(status)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "status": {
* "startBlockHeight": 543376,
* "syncedBlockHeight": 723249,
* "chainBlockHeight": 722679
* }
* }
*
*/
async status () {
try {
const response = await this.axios.get(
`${this.restURL}slp/status`,
this.axiosOptions
)
return response.data
} catch (error) {
if (error.response && error.response.data && error.response.data.error) throw new Error(error.response.data.error)
else throw error
}
}
/**
* @api PsfSlpIndexer.balance() balance()
* @apiName SLP Balance
* @apiGroup PSF SLP
* @apiDescription Return slp balance for a single address.
*
* @apiExample Example usage:
* (async () => {
* try {
* let balance = await bchjs.PsfSlpIndexer.balance('bitcoincash:qzmd5vxgh9m22m6fgvm57yd6kjnjl9qnwywsf3583n')
* console.log(balance)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* balance: {
* utxos: [
* {
* txid: 'a24a6a4abf06fabd799ecea4f8fac6a9ff21e6a8dd6169a3c2ebc03665329db9',
* vout: 1,
* type: 'token',
* qty: '1800',
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* address: 'bitcoincash:qrqy3kj7r822ps6628vwqq5k8hyjl6ey3y4eea2m4s'
* }
* ],
* txs: [
* {
* txid: '078b2c48ed1db0d5d5996f2889b8d847a49200d0a781f6aa6752f740f312688f',
* height: 717796
* },
* {
* txid: 'a24a6a4abf06fabd799ecea4f8fac6a9ff21e6a8dd6169a3c2ebc03665329db9',
* height: 717832
* }
* ],
* balances: [
* {
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* qty: '1800'
* }
* ]
* }
* }
*
*/
async balance (address) {
try {
// console.log('balance() address: ', address)
// Handle single address.
if (typeof address === 'string') {
const response = await this.axios.post(
`${this.restURL}slp/address`,
{ address },
this.axiosOptions
)
return response.data
}
throw new Error('Input address must be a string.')
} catch (error) {
if (error.response && error.response.data && error.response.data.error) throw new Error(error.response.data.error)
else throw error
}
}
/**
* @api PsfSlpIndexer.tokenStats() tokenStats()
* @apiName Token Stats
* @apiGroup PSF SLP
* @apiDescription Return list stats for a single slp token.
* The second input is a Boolean, which determins the the transaction history
* of the token is included in the returned data. The default is false.
*
* @apiExample Example usage:
* (async () => {
* try {
* let tokenStats = await bchjs.PsfSlpIndexer.tokenStats('a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2', true)
* console.log(tokenStats)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* tokenData: {
* type: 1,
* ticker: 'TROUT',
* name: "Trout's test token",
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* documentUri: 'troutsblog.com',
* documentHash: '',
* decimals: 2,
* mintBatonIsActive: true,
* tokensInCirculationBN: '100098953386',
* tokensInCirculationStr: '100098953386',
* blockCreated: 622414,
* totalBurned: '1046614',
* totalMinted: '100100000000'
* txs: [
* {
* txid: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* height: 622414,
* type: 'GENESIS',
* qty: '100000000000'
* }
* ]
* }
* }
*
*
*/
async tokenStats (tokenId, withTxHistory = false) {
try {
// Handle single address.
if (typeof tokenId === 'string') {
const response = await this.axios.post(
`${this.restURL}slp/token`,
{ tokenId, withTxHistory },
this.axiosOptions
)
return response.data
}
throw new Error('Input tokenId must be a string.')
} catch (error) {
if (error.response && error.response.data && error.response.data.error) throw new Error(error.response.data.error)
else throw error
}
}
/**
* @api PsfSlpIndexer.tx() tx()
* @apiName SLP Transaction Data
* @apiGroup PSF SLP
* @apiDescription Return slp transaction data.
*
* @apiExample Example usage:
* (async () => {
* try {
* let txData = await bchjs.PsfSlpIndexer.tx('a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2')
* console.log(txData)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* txData: {
* txid: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* hash: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* version: 2,
* size: 339,
* locktime: 0,
* vin: [
* {
* txid: '8370db30d94761ab9a11b71ecd22541151bf6125c8c613f0f6fab8ab794565a7',
* vout: 0,
* scriptSig: {
* asm: '304402207e9631c53dfc8a9a793d1916469628c6b7c5780c01c2f676d51ef21b0ba4926f022069feb471ec869a49f8d108d0aaba04e7cd36e60a7500109d86537f55698930d4[ALL|FORKID] 02791b19a39165dbd83403d6df268d44fd621da30581b0b6e5cb15a7101ed58851',
* hex: '47304402207e9631c53dfc8a9a793d1916469628c6b7c5780c01c2f676d51ef21b0ba4926f022069feb471ec869a49f8d108d0aaba04e7cd36e60a7500109d86537f55698930d4412102791b19a39165dbd83403d6df268d44fd621da30581b0b6e5cb15a7101ed58851'
* },
* sequence: 4294967295,
* address: 'bitcoincash:qpvsg9vl9a5mlf37a7n3yce6pktdctn73qwgaqm3wq',
* value: 0.00051303,
* tokenQty: 0,
* tokenQtyStr: '0',
* tokenId: null
* }
* ],
* vout: [
* {
* value: 0,
* n: 0,
* scriptPubKey: {
* asm: 'OP_RETURN 5262419 1 47454e45534953 54524f5554 54726f75742773207465737420746f6b656e 74726f757473626c6f672e636f6d 0 2 2 000000174876e800',
* hex: '6a04534c500001010747454e455349530554524f55541254726f75742773207465737420746f6b656e0e74726f757473626c6f672e636f6d4c000102010208000000174876e800',
* type: 'nulldata'
* },
* tokenQtyStr: '0',
* tokenQty: 0
* }
* ],
* hex: '0200000001a7654579abb8faf6f013c6c82561bf51115422cd1eb7119aab6147d930db7083000000006a47304402207e9631c53dfc8a9a793d1916469628c6b7c5780c01c2f676d51ef21b0ba4926f022069feb471ec869a49f8d108d0aaba04e7cd36e60a7500109d86537f55698930d4412102791b19a39165dbd83403d6df268d44fd621da30581b0b6e5cb15a7101ed58851ffffffff040000000000000000476a04534c500001010747454e455349530554524f55541254726f75742773207465737420746f6b656e0e74726f757473626c6f672e636f6d4c000102010208000000174876e80022020000000000001976a914db4d39ceb7794ffe5d06855f249e1d3a7f1b024088ac22020000000000001976a914db4d39ceb7794ffe5d06855f249e1d3a7f1b024088accec20000000000001976a9145904159f2f69bfa63eefa712633a0d96dc2e7e8888ac00000000',
* blockhash: '0000000000000000009f65225a3e12e23a7ea057c869047e0f36563a1f410267',
* confirmations: 97398,
* time: 1581773131,
* blocktime: 1581773131,
* blockheight: 622414,
* isSlpTx: true,
* tokenTxType: 'GENESIS',
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* tokenType: 1,
* tokenTicker: 'TROUT',
* tokenName: "Trout's test token",
* tokenDecimals: 2,
* tokenUri: 'troutsblog.com',
* tokenDocHash: '',
* isValidSlp: true
* }
* }
*
*/
async tx (txid) {
try {
// console.log('txid: ', txid)
// Handle single address.
if (typeof txid === 'string') {
const response = await this.axios.post(
`${this.restURL}slp/txid`,
{ txid },
this.axiosOptions
)
// console.log('response: ', response)
return response.data
}
throw new Error('Input txid must be a string.')
} catch (error) {
// console.log('error: ', error)
// Case: txid is not stored in the psf-slp-indexer tx database.
// Response: If it's not in the database, then it can be assumed the TX
// is not a token TX?
if (
error.response &&
error.response.data &&
error.response.data.error &&
error.response.data.error.includes('Key not found in database')
) {
// console.log(
// 'TX not found in psf-slp-indexer. Retrieving from full node.'
// )
// Check if this txid belongs to a blacklisted token.
const isInBlacklist = await this.checkBlacklist(txid)
// console.log('isInBlacklist: ', isInBlacklist)
// Get the TX Details from the full node.
const txDetails = await this.rawTransaction.getTxData(txid)
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
// Add blockheight, height, time, and blocktime to the txDetails object.
if (txDetails.height === null) {
// Get current block height and increment by 1
const currentBlockHeight = await this.blockchain.getBlockCount()
const estimatedHeight = currentBlockHeight + 1
// Set height and blockheight
txDetails.height = estimatedHeight
txDetails.blockheight = estimatedHeight
// Set time and blocktime to current unix timestamp
const currentTime = Math.floor(Date.now() / 1000)
txDetails.time = currentTime
txDetails.blocktime = currentTime
}
if (isInBlacklist) {
txDetails.isValidSlp = null
} else {
txDetails.isValidSlp = false
}
const outObj = {
txData: txDetails
}
return outObj
} else throw error
}
}
// Check if the txid has an OP_RETURN containing a tokenID that is in the
// blacklist. In that case, the isValidSlp property should be marked as
// null, and not false.
async checkBlacklist (txid) {
try {
// TODO: Add endpoint to psf-slp-indexer to retrieve current blacklist.
// This should be done once at startup, and not each time this function
// is called.
const blacklist = [
'dd21be4532d93661e8ffe16db6535af0fb8ee1344d1fef81a193e2b4cfa9fbc9'
]
const outTokenData = await this.slpUtils.decodeOpReturn(txid)
// console.log('outTokenData: ', outTokenData)
// Loop through each token in the blacklist.
for (let i = 0; i < blacklist.length; i++) {
// If a match is found, return true.
if (outTokenData.tokenId === blacklist[i]) {
return true
}
}
// By default, return false.
return false
} catch (err) {
// console.log(err)
// Exit quietly.
return false
}
}
/**
* @api PsfSlpIndexer.getTokenData() getTokenData()
* @apiName Token Data
* @apiGroup PSF SLP
* @apiDescription Get mutable and immutable data if the token contains them.
*
* @apiExample Example usage:
* (async () => {
* try {
* let tokenData = await bchjs.PsfSlpIndexer.getTokenData('a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2')
* console.log(tokenData)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* genesisData: {
* type: 1,
* ticker: 'TROUT',
* name: "Trout's test token",
* tokenId: 'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2',
* documentUri: 'troutsblog.com',
* documentHash: '',
* decimals: 2,
* mintBatonIsActive: true,
* tokensInCirculationBN: '100098953386',
* tokensInCirculationStr: '100098953386',
* blockCreated: 622414,
* totalBurned: '1046614',
* totalMinted: '100100000000'
* ]
* },
* immutableData :{
* issuer:"FullStack.cash.",
* website:"https://fullstack.cash/",
* dateCreated:"2022-01-11"
* },
* mutableData :{
* "tokenIcon":"https://gateway.ipfs.io/ipfs/bafybeiehitanirn5gmhqjg44xrmdtomn4n5lu5yjoepsvgpswk5mggaw6i/LP_logo-1.png",
* "about":"Mutable data managed with npm package: https://www.npmjs.com/package/slp-mutable-data"
* }
* }
*
*/
async getTokenData (tokenId, withTxHistory = false) {
try {
const url = `${this.restURL}slp/token/data`
// console.log(`url: ${url}`)
// Handle single address.
if (typeof tokenId === 'string') {
const response = await this.axios.post(
// 'https://bchn.fullstack.cash/v5/psf/slp/token/data/',
url,
{ tokenId, withTxHistory },
this.axiosOptions
)
return response.data
}
throw new Error('Input tokenId must be a string.')
} catch (error) {
if (error.response && error.response.data && error.response.data.error) throw new Error(error.response.data.error)
else throw error
}
}
/**
* @api PsfSlpIndexer.getTokenData2() getTokenData2()
* @apiName Token Data
* @apiGroup PSF SLP
* @apiDescription Get token icon and other media associated with a token.
*
* Get the icon for a token, given it's token ID.
* This function expects a string input of a token ID property.
* This function returns an object with a tokenIcon property that contains
* the URL to the icon.
*
* The output object always have these properties:
* - tokenIcon: A url to the token icon, if it exists.
* - tokenStats: Data about the token from psf-slp-indexer.
* - optimizedTokenIcon: An alternative, potentially more optimal, url to the token icon, if it exists.
* - iconRepoCompatible: true if the token icon is available via token.bch.sx
* - ps002Compatible: true if the token icon is compatible with PS007 specification.
*
* @apiExample Example usage:
* (async () => {
* try {
* let tokenData = await bchjs.PsfSlpIndexer.getTokenData2('a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2')
* console.log(tokenData)
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* tokenStats: {
* type: 1,
* ticker: 'CTAIA006',
* name: 'CTAIA006 - AI Art by Chris Troutner',
* tokenId: '0e4543f820699294ab57e02ee2b1815a8bbc7b17a4333e4a138034e4b2324a61',
* documentUri: 'ipfs://bafybeia5yuq7rg6jmwquako7t277cwrobcunz7cumqrv4wn6bgfvthemku',
* documentHash: '78a00e9db312b8fff4e5c37cf592be83e6bab7f3bd5a54c9545bad5d4f3ee0f5',
* decimals: 0,
* mintBatonIsActive: false,
* tokensInCirculationBN: '1',
* tokensInCirculationStr: '1',
* blockCreated: 757507,
* totalBurned: '0',
* totalMinted: '1'
* },
* mutableData: {
* tokenIcon: 'https://bafybeihiv5jvlhoymmbous3h2akotogj6b7hruhjcj3zq7dsfteimuuttm.ipfs.w3s.link/whale-night-sky-01.png',
* fullSizedUrl: '',
* about: 'This NFT was created using the PSF Token Studio at https://nft-creator.fullstack.cash',
* userData: ''
* },
* immutableData: {
* issuer: 'http://psfoundation.cash',
* website: 'https://nft-creator.fullstack.cash',
* dateCreated: '9/12/2022, 5:17:38 PM',
* userData: '{\n' +
* ' "title": "CTAIA006 - AI Art by Chris Troutner",\n' +
* ' "about": "AI generated art. Generated from DALL-E at https://labs.openai.com",\n' +
* ' "prompt": "whale swimming through a sky full of stars",\n' +
* ' "algorithm": "DALL-E (stable diffusion)",\n' +
* ' "set": "1-of-2"\n' +
* '}'
* },
* tokenIcon: 'https://bafybeihiv5jvlhoymmbous3h2akotogj6b7hruhjcj3zq7dsfteimuuttm.ipfs.w3s.link/whale-night-sky-01.png',
* fullSizedUrl: '',
* optimizedTokenIcon: 'https://p2wdb-gateway-678.fullstack.cash/ipfs/bafybeihiv5jvlhoymmbous3h2akotogj6b7hruhjcj3zq7dsfteimuuttm/whale-night-sky-01.png',
* optimizedFullSizedUrl: '',
* iconRepoCompatible: false,
* ps002Compatible: true
* }
*
*/
async getTokenData2 (tokenId, updateCache = false) {
try {
const url = `${this.restURL}slp/token/data2`
// console.log(`url: ${url}`)
// Handle single address.
if (typeof tokenId === 'string') {
const response = await this.axios.post(
// 'https://bchn.fullstack.cash/v5/psf/slp/token/data/',
url,
{ tokenId, updateCache },
this.axiosOptions
)
return response.data
}
throw new Error('Input tokenId must be a string.')
} catch (error) {
// console.log('error: ', error)
if (error.response && error.response.data && error.response.data.error) throw new Error(error.response.data.error)
else throw error
}
}
}
export default PsfSlpIndexer
+87 -145
View File
@@ -1,38 +1,20 @@
const axios = require('axios')
import axios from 'axios'
const SlpUtils = require('./slp/utils')
let _this
// let _this
class RawTransactions {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
// Encapsulate dependencies
this.axios = axios
// Dependencies
this.slpUtils = new SlpUtils(config)
_this = this
// Use the shared axios instance if provided, otherwise fall back to axios
this.axios = config.axios || axios
}
/**
@@ -101,9 +83,9 @@ class RawTransactions {
try {
// Single hex
if (typeof hex === 'string') {
const response = await axios.get(
`${this.restURL}rawtransactions/decodeRawTransaction/${hex}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/rawtransactions/decodeRawTransaction/${hex}`,
this.axiosOptions
)
return response.data
@@ -112,22 +94,21 @@ class RawTransactions {
} else if (Array.isArray(hex)) {
const options = {
method: 'POST',
url: `${this.restURL}rawtransactions/decodeRawTransaction`,
url: `${this.restURL}full-node/rawtransactions/decodeRawTransaction`,
data: {
hexes: hex
},
headers: {
authorization: `Token ${_this.apiToken}`
}
headers: this.axiosOptions.headers
}
const response = await axios(options)
const response = await this.axios(options)
return response.data
}
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
if (error.error) throw new Error(error.error)
else if (error.response && error.response.data) throw error.response.data
else throw error
}
}
@@ -170,31 +151,30 @@ class RawTransactions {
try {
if (typeof script === 'string') {
const response = await axios.get(
`${this.restURL}rawtransactions/decodeScript/${script}`,
_this.axiosOptions
const response = await this.axios.get(
`${this.restURL}full-node/rawtransactions/decodeScript/${script}`,
this.axiosOptions
)
return response.data
} else if (Array.isArray(script)) {
const options = {
method: 'POST',
url: `${this.restURL}rawtransactions/decodeScript`,
url: `${this.restURL}full-node/rawtransactions/decodeScript`,
data: {
hexes: script
},
headers: {
authorization: `Token ${this.apiToken}`
}
headers: this.axiosOptions.headers
}
const response = await axios(options)
const response = await this.axios(options)
return response.data
}
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
if (error.error) throw new Error(error.error)
else if (error.response && error.response.data) throw error.response.data
else throw error
}
}
@@ -266,32 +246,42 @@ class RawTransactions {
async getRawTransaction (txid, verbose = false, usrObj = null) {
try {
if (typeof txid === 'string') {
const response = await axios.get(
`${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=${verbose}`,
_this.axiosOptions
// console.log(
// 'getRawTransaction() this.axiosOptions: ',
// this.axiosOptions
// )
const response = await this.axios.get(
`${this.restURL}full-node/rawtransactions/getRawTransaction/${txid}?verbose=${verbose}`,
this.axiosOptions
)
return response.data
} else if (Array.isArray(txid)) {
const options = {
method: 'POST',
url: `${this.restURL}rawtransactions/getRawTransaction`,
url: `${this.restURL}full-node/rawtransactions/getRawTransaction`,
data: {
txids: txid,
verbose: verbose,
verbose,
usrObj // pass user data when making an internal call.
},
headers: _this.axiosOptions.headers
headers: this.axiosOptions.headers
}
const response = await axios(options)
const response = await this.axios(options)
return response.data
}
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.error) throw new Error(error.error)
// This case handles rate limit errors.
if (error.response && error.response.data && error.response.data.error) {
throw new Error(error.response.data.error)
} else if (error.response && error.response.data) {
throw error.response.data
} else throw error
}
}
@@ -316,6 +306,9 @@ class RawTransactions {
const inputTxid = vin.txid
const inputVout = vin.vout
// TODO: Coinbase TXs have no input transaction. Figure out how to
// handle this corner case.
// Get the TX details for the input, in order to retrieve the address of
// the sender.
const txDetailsParent = await this.getRawTransaction(inputTxid, true)
@@ -328,14 +321,21 @@ class RawTransactions {
retArray.push({
vin: i,
address: voutSender.scriptPubKey.addresses[0]
address: voutSender.scriptPubKey.addresses[0],
value: voutSender.value
})
}
return retArray
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
if (error.error) throw new Error(error.error)
// This case handles rate limit errors.
if (error.response && error.response.data && error.response.data.error) {
throw new Error(error.response.data.error)
} else if (error.response && error.response.data) {
throw error.response.data
} else throw error
}
}
@@ -368,104 +368,45 @@ class RawTransactions {
// Appends the BCH address to the inputs of the transaction.
async getTxData (txid) {
try {
// console.log('getTxData() txid: ', txid)
if (typeof txid !== 'string') {
throw new Error('Input must be a string or array of strings.')
throw new Error(
'Input to raw-transaction.js/getTxData() must be a string containg a TXID.'
)
}
// Get the TX details for the transaction under consideration.
const txDetails = await this.getRawTransaction(txid, true)
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
const inAddrs = await this._getInputAddrs(txDetails)
// console.log(`inAddrs: ${JSON.stringify(inAddrs, null, 2)}`)
// Add the input address to the transaction data.
for (let i = 0; i < inAddrs.length; i++) {
txDetails.vin[i].address = inAddrs[i].address
}
return txDetails
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
// Wraps getTxData(), but also appends SLP token information to each input
// and output of the transaction. This is a very API-heavy call.
// Returns false if the txid is not an SLP transaction.
//
// Warning! This is a prototype function and the output can change at any time
// without reflecting a change in the semantic version. DO NOT USE IN PRODUCTION.
async getTxDataSlp (txid) {
try {
if (typeof txid !== 'string') {
throw new Error('Input must be a string or array of strings.')
}
const txDetails = await this.getTxData(txid)
// First get the token information for the output. If that fails, then
// this is not an SLP transaction, and this method can return false.
let outTokenData
try {
outTokenData = await this.slpUtils.decodeOpReturn(txid)
// console.log(`outTokenData: ${JSON.stringify(outTokenData, null, 2)}`)
const inAddrs = await this._getInputAddrs(txDetails)
// console.log(`inAddrs: ${JSON.stringify(inAddrs, null, 2)}`)
// Add token information to the tx details object.
txDetails.tokenTxType = outTokenData.txType
txDetails.tokenId = outTokenData.tokenId
// Add the token quantity to each output.
for (let i = 0; i < outTokenData.amounts.length; i++) {
txDetails.vout[i + 1].tokenQty = outTokenData.amounts[i]
}
// Loop through each input and retrieve the token data.
for (let i = 0; i < txDetails.vin.length; i++) {
const thisVin = txDetails.vin[i]
try {
// If decodeOpReturn() throws an error, then this input is not
// from an SLP transaction and can be ignored.
const inTokenData = await this.slpUtils.decodeOpReturn(thisVin.txid)
// console.log(
// `vin[${i}] tokenData: ${JSON.stringify(inTokenData, null, 2)}`
// )
// Get the appropriate vout token amount. This may throw an error,
// which means this Vin is not actually a token UTXO, it was just
// associated with a previous token TX.
const tokenQty = inTokenData.amounts[thisVin.vout - 1]
// console.log(`tokenQty: ${JSON.stringify(tokenQty, null, 2)}`)
if (tokenQty) {
thisVin.tokenQty = tokenQty
// txDetails.vin[i].tokenQty = tokenQty
} else {
thisVin.tokenQty = null
}
} catch (err) {
// console.log('catch 2: ', err)
// If decodeOpReturn() throws an error, then this input is not
// from an SLP transaction and can be ignored.
// thisVin.tokenQty = null
thisVin.tokenQty = null
continue
}
// console.log(
// `2: txDetails.vin[i]: ${JSON.stringify(txDetails.vin[i], null, 2)}`
// )
// Add the input address to the transaction data.
for (let i = 0; i < inAddrs.length; i++) {
txDetails.vin[i].address = inAddrs[i].address
txDetails.vin[i].value = inAddrs[i].value
}
} catch (err) {
// console.log('catch 1: ', err)
return false
// Coinbase transactions will throw an error. Just ignore them and
// pass back the raw transaction data.
/* exit quietly */
}
// console.log(`txDetails: ${JSON.stringify(txDetails, null, 2)}`)
return txDetails
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
// console.log('error: ', error)
if (error.error) throw new Error(error.error)
// This case handles rate limit errors.
if (error.response && error.response.data && error.response.data.error) {
throw new Error(error.response.data.error)
} else if (error.response && error.response.data) {
throw error.response.data
} else throw error
}
}
@@ -506,8 +447,8 @@ class RawTransactions {
// Single tx hex.
if (typeof hex === 'string') {
const response = await this.axios.get(
`${this.restURL}rawtransactions/sendRawTransaction/${hex}`,
_this.axiosOptions
`${this.restURL}full-node/rawtransactions/sendRawTransaction/${hex}`,
this.axiosOptions
)
if (response.data === '66: insufficient priority') {
@@ -524,23 +465,24 @@ class RawTransactions {
} else if (Array.isArray(hex)) {
const options = {
method: 'POST',
url: `${this.restURL}rawtransactions/sendRawTransaction`,
url: `${this.restURL}full-node/rawtransactions/sendRawTransaction`,
data: {
hexes: hex
},
headers: _this.axiosOptions.headers
headers: this.axiosOptions.headers
}
const response = await _this.axios(options)
const response = await this.axios(options)
return response.data
}
throw new Error('Input hex must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
if (error.error) throw new Error(error.error)
else if (error.response && error.response.data) throw error.response.data
else throw error
}
}
}
module.exports = RawTransactions
export default RawTransactions
+5 -16
View File
@@ -1,24 +1,13 @@
const schnorr = require('bip-schnorr')
import schnorr from 'bip-schnorr'
class Schnorr {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
}
@@ -509,4 +498,4 @@ class Schnorr {
}
}
module.exports = Schnorr
export default Schnorr
+128 -3
View File
@@ -1,5 +1,130 @@
const Bitcoin = require('@psf/bitcoincashjs-lib')
const opcodes = require('@psf/bitcoincash-ops')
import Bitcoin from '@psf/bitcoincashjs-lib'
// Inline opcodes data to avoid fs/import.meta issues in browser builds.
// This data is from @psf/bitcoincash-ops/index.json
const opcodes = {
OP_FALSE: 0,
OP_0: 0,
OP_PUSHDATA1: 76,
OP_PUSHDATA2: 77,
OP_PUSHDATA4: 78,
OP_1NEGATE: 79,
OP_RESERVED: 80,
OP_TRUE: 81,
OP_1: 81,
OP_2: 82,
OP_3: 83,
OP_4: 84,
OP_5: 85,
OP_6: 86,
OP_7: 87,
OP_8: 88,
OP_9: 89,
OP_10: 90,
OP_11: 91,
OP_12: 92,
OP_13: 93,
OP_14: 94,
OP_15: 95,
OP_16: 96,
OP_NOP: 97,
OP_VER: 98,
OP_IF: 99,
OP_NOTIF: 100,
OP_VERIF: 101,
OP_VERNOTIF: 102,
OP_ELSE: 103,
OP_ENDIF: 104,
OP_VERIFY: 105,
OP_RETURN: 106,
OP_TOALTSTACK: 107,
OP_FROMALTSTACK: 108,
OP_2DROP: 109,
OP_2DUP: 110,
OP_3DUP: 111,
OP_2OVER: 112,
OP_2ROT: 113,
OP_2SWAP: 114,
OP_IFDUP: 115,
OP_DEPTH: 116,
OP_DROP: 117,
OP_DUP: 118,
OP_NIP: 119,
OP_OVER: 120,
OP_PICK: 121,
OP_ROLL: 122,
OP_ROT: 123,
OP_SWAP: 124,
OP_TUCK: 125,
OP_CAT: 126,
OP_SPLIT: 127,
OP_NUM2BIN: 128,
OP_BIN2NUM: 129,
OP_SIZE: 130,
OP_INVERT: 131,
OP_AND: 132,
OP_OR: 133,
OP_XOR: 134,
OP_EQUAL: 135,
OP_EQUALVERIFY: 136,
OP_RESERVED1: 137,
OP_RESERVED2: 138,
OP_1ADD: 139,
OP_1SUB: 140,
OP_2MUL: 141,
OP_2DIV: 142,
OP_NEGATE: 143,
OP_ABS: 144,
OP_NOT: 145,
OP_0NOTEQUAL: 146,
OP_ADD: 147,
OP_SUB: 148,
OP_MUL: 149,
OP_DIV: 150,
OP_MOD: 151,
OP_LSHIFT: 152,
OP_RSHIFT: 153,
OP_BOOLAND: 154,
OP_BOOLOR: 155,
OP_NUMEQUAL: 156,
OP_NUMEQUALVERIFY: 157,
OP_NUMNOTEQUAL: 158,
OP_LESSTHAN: 159,
OP_GREATERTHAN: 160,
OP_LESSTHANOREQUAL: 161,
OP_GREATERTHANOREQUAL: 162,
OP_MIN: 163,
OP_MAX: 164,
OP_WITHIN: 165,
OP_RIPEMD160: 166,
OP_SHA1: 167,
OP_SHA256: 168,
OP_HASH160: 169,
OP_HASH256: 170,
OP_CODESEPARATOR: 171,
OP_CHECKSIG: 172,
OP_CHECKSIGVERIFY: 173,
OP_CHECKMULTISIG: 174,
OP_CHECKMULTISIGVERIFY: 175,
OP_NOP1: 176,
OP_NOP2: 177,
OP_CHECKLOCKTIMEVERIFY: 177,
OP_NOP3: 178,
OP_CHECKSEQUENCEVERIFY: 178,
OP_NOP4: 179,
OP_NOP5: 180,
OP_NOP6: 181,
OP_NOP7: 182,
OP_NOP8: 183,
OP_NOP9: 184,
OP_NOP10: 185,
OP_CHECKDATASIG: 186,
OP_CHECKDATASIGVERIFY: 187,
OP_REVERSEBYTES: 188,
OP_PUBKEYHASH: 253,
OP_PUBKEY: 254,
OP_INVALIDOPCODE: 255
}
class Script {
constructor () {
@@ -240,4 +365,4 @@ class Script {
}
}
module.exports = Script
export default Script
+5 -5
View File
@@ -1,9 +1,9 @@
const BCHJSAddress = require('../address')
import BCHJSAddress from '../address.js'
import bchaddrjs from 'bchaddrjs-slp'
// const bchAddress = new BCHJSAddress()
let bchAddress
const bchaddrjs = require('bchaddrjs-slp')
class Address extends BCHJSAddress {
constructor (config) {
super(config)
@@ -36,7 +36,7 @@ class Address extends BCHJSAddress {
* bchjs.SLP.Address.toSLPAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
* // simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp
*
* // tesnet legacy
* // testnet legacy
* bchjs.SLP.Address.toSLPAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
* // slptest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqauyclpwv
*
@@ -661,4 +661,4 @@ class Address extends BCHJSAddress {
}
}
module.exports = Address
export default Address
+4 -4
View File
@@ -1,9 +1,9 @@
// const BCHJS = require("../bch-js")
// import BCHJS from "../bch-js.js"
// const bchjs = new BCHJS()
const BCHJSECPair = require('../ecpair')
import BCHJSECPair from '../ecpair.js'
const bchaddrjs = require('bchaddrjs-slp')
import bchaddrjs from 'bchaddrjs-slp'
class ECPair extends BCHJSECPair {
/*
@@ -31,4 +31,4 @@ class ECPair extends BCHJSECPair {
}
}
module.exports = ECPair
export default ECPair
+14 -7
View File
@@ -8,16 +8,21 @@
(Parent) token.
*/
const Address = require('./address')
// Public npm libraries
// import axios from 'axios'
// const BigNumber = require('bignumber.js')
const slpMdm = require('slp-mdm')
// Local libraries.
import Address from './address.js'
// import BigNumber from 'bignumber.js'
import slpMdm from 'slp-mdm'
import TransactionBuilder from '../transaction-builder.js'
// let _this
// const addy = new Address()
let addy
const TransactionBuilder = require('../transaction-builder')
class TokenType1 {
class Nft1 {
constructor (config) {
this.restURL = config.restURL
@@ -25,6 +30,8 @@ class TokenType1 {
// Instantiate the transaction builder.
TransactionBuilder.setAddress(addy)
// _this = this
}
/**
@@ -140,7 +147,7 @@ class TokenType1 {
// Loop through the tokenUtxos array and find the minting baton.
let mintBatonUtxo
for (let i = 0; i < tokenUtxos.length; i++) {
if (tokenUtxos[i].utxoType === 'minting-baton') {
if (tokenUtxos[i].utxoType === 'minting-baton' || tokenUtxos[i].type === 'baton') {
mintBatonUtxo = tokenUtxos[i]
}
}
@@ -414,4 +421,4 @@ class TokenType1 {
}
}
module.exports = TokenType1
export default Nft1
+12 -23
View File
@@ -7,43 +7,32 @@
// imports
// require deps
// const BCHJS = require("../bch-js")
const Address = require('./address')
const ECPair = require('./ecpair')
// const HDNode = require("./hdnode")
const TokenType1 = require('./tokentype1')
const NFT1 = require('./nft1')
const Utils = require('./utils')
// import BCHJS from "../bch-js.js"
import Address from './address.js'
import ECPair from './ecpair.js'
// import HDNode from "./hdnode.js"
import TokenType1 from './tokentype1.js'
import NFT1 from './nft1.js'
import Utils from './utils.js'
// SLP is a superset of BITBOX
class SLP {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
this.Address = new Address(config)
this.ECPair = ECPair
this.TokenType1 = new TokenType1(config)
this.NFT1 = new NFT1(this.restURL)
this.NFT1 = new NFT1(config)
this.Utils = new Utils(config)
}
}
module.exports = SLP
export default SLP
+36 -36
View File
@@ -2,41 +2,30 @@
This library handles the OP_RETURN of SLP TokenType1 transactions.
*/
// const BCHJS = require("../bch-js")
// import BCHJS from "../bch-js.js"
// const bchjs = new BCHJS()
const Address = require('./address')
const Script = require('../script')
import Address from './address.js'
import Script from '../script.js'
const BigNumber = require('bignumber.js')
const slpMdm = require('slp-mdm')
const axios = require('axios')
import BigNumber from 'bignumber.js'
import slpMdm from 'slp-mdm'
import axios from 'axios'
import TransactionBuilder from '../transaction-builder.js'
// const addy = new Address()
let addy
const TransactionBuilder = require('../transaction-builder')
let _this // local global
class TokenType1 {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
@@ -125,13 +114,13 @@ class TokenType1 {
// console.log('baseChange: ', baseChange)
// Check for potential burns
const outputQty = new BigNumber(baseChange).plus(
new BigNumber(baseQty)
)
const outputQty = new BigNumber(baseChange).plus(new BigNumber(baseQty))
const inputQty = new BigNumber(totalTokens)
const tokenOutputDelta = outputQty.minus(inputQty).toString() !== '0'
if (tokenOutputDelta) {
throw new Error('Token transaction inputs do not match outputs, cannot send transaction')
throw new Error(
'Token transaction inputs do not match outputs, cannot send transaction'
)
}
// Generate the OP_RETURN as a Buffer.
@@ -152,7 +141,9 @@ class TokenType1 {
const tokenSingleOutputError =
noChangeOutputQty.minus(noChangeInputQty).toString() !== '0'
if (tokenSingleOutputError) {
throw new Error('Token transaction inputs do not match outputs, cannot send transaction')
throw new Error(
'Token transaction inputs do not match outputs, cannot send transaction'
)
}
// Generate the OP_RETURN as a Buffer.
@@ -285,9 +276,15 @@ class TokenType1 {
try {
// TODO: Add input validation.
let baseQty = new BigNumber(configObj.initialQty).times(
10 ** configObj.decimals
)
let baseQty
if (configObj.decimals !== 0) {
baseQty = new BigNumber(configObj.initialQty).times(
10 ** configObj.decimals
)
} else {
baseQty = new BigNumber(configObj.initialQty)
}
baseQty = baseQty.absoluteValue()
baseQty = Math.floor(baseQty)
baseQty = baseQty.toString()
@@ -367,20 +364,21 @@ class TokenType1 {
if (!Array.isArray(tokenUtxos)) {
throw new Error('tokenUtxos must be an array.')
}
if (!mintQty) {
throw new Error('mintQty must be a positive number.')
}
// Loop through the tokenUtxos array and find the minting baton.
let mintBatonUtxo
for (let i = 0; i < tokenUtxos.length; i++) {
if (tokenUtxos[i].utxoType === 'minting-baton') {
if (tokenUtxos[i].utxoType === 'minting-baton' || tokenUtxos[i].type === 'baton') {
mintBatonUtxo = tokenUtxos[i]
}
}
// Throw an error if the minting baton could not be found.
if (!mintBatonUtxo) {
throw new Error(
'Minting baton could not be found in tokenUtxos array.'
)
throw new Error('Minting baton could not be found in tokenUtxos array.')
}
const tokenId = mintBatonUtxo.tokenId
@@ -389,7 +387,7 @@ class TokenType1 {
if (!tokenId) {
throw new Error('tokenId property not found in mint-baton UTXO.')
}
if (!decimals) {
if (!decimals && decimals !== 0) {
throw new Error('decimals property not found in mint-baton UTXO.')
}
@@ -398,6 +396,8 @@ class TokenType1 {
baseQty = Math.floor(baseQty)
baseQty = baseQty.toString()
if (isNaN(baseQty)) throw new Error('baseQty is non a number!')
// Signal that the baton should be passed or detroyed.
let batonVout = 2
if (destroyBaton) batonVout = null
@@ -454,7 +454,7 @@ class TokenType1 {
const result = await _this.axios.post(
`${this.restURL}slp/generatesendopreturn`,
data,
_this.axiosOptions
this.axiosOptions
)
const slpSendObj = result.data
@@ -472,4 +472,4 @@ class TokenType1 {
}
}
module.exports = TokenType1
export default TokenType1
+14 -1758
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1,7 +1,7 @@
const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require('@psf/coininfo')
const bip66 = require('bip66')
const bip68 = require('bc-bip68')
import Bitcoin from '@psf/bitcoincashjs-lib'
import coininfo from '@psf/coininfo'
import bip66 from 'bip66'
import bip68 from 'bc-bip68'
class TransactionBuilder {
static setAddress (address) {
@@ -163,4 +163,4 @@ class TransactionBuilder {
}
}
module.exports = TransactionBuilder
export default TransactionBuilder
+80
View File
@@ -0,0 +1,80 @@
/*
High-level functions for working with Transactions
*/
// Global npm libraries
// const BigNumber = require('bignumber.js')
// Local libraries
import RawTransaction from './raw-transactions.js'
import SlpUtils from './slp/utils.js'
import Blockchain from './blockchain.js'
import PsfSlpIndexer from './psf-slp-indexer.js'
class Transaction {
constructor (config = {}) {
// Encapsulate dependencies
this.slpUtils = new SlpUtils(config)
this.rawTransaction = new RawTransaction(config)
this.blockchain = new Blockchain(config)
this.psfSlpIndexer = new PsfSlpIndexer(config)
}
/**
* @api Transaction.get() get()
* @apiName get
* @apiGroup Transaction
* @apiDescription
* Returns an object of transaction data, including addresses for input UTXOs.
* If it is a SLP token transaction, the token information for inputs and
* outputs will also be included.
*
*
* @apiExample Example usage:
* (async () => {
* try {
* let txData = await bchjs.Transaction.get("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
* console.log(txData);
* } catch(error) {
* console.error(error)
* }
* })()
*/
async get (txid) {
// console.log('transaction.get() txid: ', txid)
return await this.psfSlpIndexer.tx(txid)
}
/**
* @api Transaction.getTokenInfo() getTokenInfo()
* @apiName getTokenInfo
* @apiGroup Transaction
* @apiDescription
* Given the TXID of a token transaction, it will return data about that
* token by retrieving the data from the Genesis transaction and docoding
* the OP_RETURN.
*
*
* @apiExample Example usage:
* (async () => {
* try {
* let txData = await bchjs.Transaction.getTokenInfo("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
* console.log(txData);
* } catch(error) {
* console.error(error)
* }
* })()
*/
// A wrapper for decodeOpReturn(). Returns false if txid is not an SLP tx.
// Returns the token data if the txid is an SLP tx.
async getTokenInfo (txid) {
try {
const tokenData = await this.slpUtils.decodeOpReturn(txid)
return tokenData
} catch (err) {
return false
}
}
}
export default Transaction
+60 -102
View File
@@ -1,34 +1,21 @@
const axios = require('axios')
// import axios from 'axios'
let _this
// let _this
class Util {
constructor (config) {
this.restURL = config.restURL
this.apiToken = config.apiToken
this.authToken = config.authToken
if (this.authToken) {
// Add Basic Authentication token to the authorization header.
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
} else {
// Add JWT token to the authorization header.
this.axiosOptions = {
headers: {
authorization: `Token ${this.apiToken}`
}
this.axiosOptions = {
headers: {
authorization: this.authToken
}
}
_this = this
}
/**
* @api util.floor8() floor8()
* @api Util.floor8() floor8()
* @apiName floor8
* @apiGroup Util
* @apiDescription Round a number down to 8 decimal places.
@@ -63,7 +50,7 @@ class Util {
}
/**
* @api util.floor2() floor2()
* @api Util.floor2() floor2()
* @apiName floor2
* @apiGroup Util
* @apiDescription Round a number down to 2 decimal places.
@@ -98,7 +85,7 @@ class Util {
}
/**
* @api util.chunk20() chunk20()
* @api Util.chunk20() chunk20()
* @apiName chunk20
* @apiGroup Util
* @apiDescription chunk up an array into multiple arrays of 20 elements each.
@@ -151,7 +138,57 @@ class Util {
}
/**
* @api util.sleep() sleep()
* @api Util.chunk100() chunk100()
* @apiName chunk100
* @apiGroup Util
* @apiDescription chunk up an array into multiple arrays of 100 elements each.
* Input: arrayToSlice - a one-dimensional array of elements.
* Returns a two-dimensional array. An array of 100-element arrays.
*
* @apiExample Example usage:
* (async () => {
* try {
* const bigArray = [0,1,2,3,4,5,6,7,8,9,10,...,148, 149, 150]
*
* const chunked = bchjs.Util.chunk20(bigArray)
* console.log(chunked)
* } catch(error) {
* console.error(error)
* }
* })()
*
* // returns
* [
* [0,1,2,3,4,5,6,7,8,9,10,11,...,98,99],
* [100,101,102,...,148,149,150]
* ]
*/
chunk100 (arrayToSlice) {
try {
// Validate inputs
if (!Array.isArray(arrayToSlice)) {
throw new Error('input must be an array')
}
let offset = 0
const result = []
// Loop over the array and slice off chunks of 100 elements.
while (offset < arrayToSlice.length) {
const chunk = arrayToSlice.slice(offset, offset + 100)
result.push(chunk)
offset = offset + 100
}
return result
} catch (err) {
console.error('Error in chunk100()')
throw err
}
}
/**
* @api Util.sleep() sleep()
* @apiName sleep
* @apiGroup Util
* @apiDescription Promise-based delay.
@@ -173,85 +210,6 @@ class Util {
sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* @api util.validateAddress() validateAddress()
* @apiName Validate Address.
* @apiGroup Util
* @apiDescription Return information about the given bitcoin address.
*
* @apiExample Example usage:
* (async () => {
* try {
* let validateAddress = await bchjs.Util.validateAddress("bitcoincash:qzc86hrdufhcwlyzk7k82x77kfs2myekn57nv9cw5f");
* console.log(validateAddress);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // { isvalid: true,
* // address: '17fshh33qUze2yifiJ2sXgijSMzJ2KNEwu',
* // scriptPubKey: '76a914492ae280d70af33acf0ae7cd329b961e65e9cbd888ac',
* // ismine: true,
* // iswatchonly: false,
* // isscript: false,
* // pubkey: '0312eeb9ae5f14c3cf43cece11134af860c2ef7d775060e3a578ceec888acada31',
* // iscompressed: true,
* // account: 'Test' }
*
* (async () => {
* try {
* let validateAddress = await bchjs.Util.validateAddress(["bitcoincash:qzc86hrdufhcwlyzk7k82x77kfs2myekn57nv9cw5f"]);
* console.log(validateAddress);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // [{ isvalid: true,
* // address: '17fshh33qUze2yifiJ2sXgijSMzJ2KNEwu',
* // scriptPubKey: '76a914492ae280d70af33acf0ae7cd329b961e65e9cbd888ac',
* // ismine: true,
* // iswatchonly: false,
* // isscript: false,
* // pubkey: '0312eeb9ae5f14c3cf43cece11134af860c2ef7d775060e3a578ceec888acada31',
* // iscompressed: true,
* // account: 'Test' }]
*/
async validateAddress (address) {
try {
// Single block
if (typeof address === 'string') {
const response = await axios.get(
`${this.restURL}util/validateAddress/${address}`,
_this.axiosOptions
)
return response.data
// Array of blocks.
} else if (Array.isArray(address)) {
const options = {
method: 'POST',
url: `${this.restURL}util/validateAddress`,
data: {
addresses: address
},
headers: {
authorization: `Token ${this.apiToken}`
}
}
const response = await axios(options)
return response.data
}
throw new Error('Input must be a string or array of strings.')
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
}
module.exports = Util
export default Util
+283 -202
View File
@@ -6,26 +6,40 @@
*/
// Local libraries
const Electrumx = require('./electrumx')
const Slp = require('./slp/slp')
import Electrumx from './electrumx.js'
import Slp from './slp/slp.js'
import PsfSlpIndexer from './psf-slp-indexer.js'
import BigNumber from 'bignumber.js'
import Blockchain from './blockchain.js'
class UTXO {
constructor (config) {
constructor (config = {}) {
// Encapsulate dependencies for easier mocking.
this.electrumx = new Electrumx(config)
this.slp = new Slp(config)
this.psfSlpIndexer = new PsfSlpIndexer(config)
this.BigNumber = BigNumber
this.blockchain = new Blockchain(config)
// Bind 'this' object to all subfunctions.
this.get = this.get.bind(this)
this.hydrateTokenData = this.hydrateTokenData.bind(this)
this.findBiggestUtxo = this.findBiggestUtxo.bind(this)
this.isValid = this.isValid.bind(this)
}
/**
* @api Utxo.get() get()
* @apiName get
* @apiGroup UTXO
* @apiDescription Get UTXOs for an address
* @apiDescription Get UTXOs for an address (from psf-slp-indexer)
*
* Given an address, this function will return an object with thre following
* properties:
* - address: "" - the address these UTXOs are associated with
* - bchUtxos: [] - UTXOs confirmed to be spendable as normal BCH
* - infoUtxos: [] - UTXOs under of 1000 sats or less that can not be categorized
* as another type of UTXO (like a token).
* - nullUtxo: [] - UTXOs that did not pass SLP validation. Should be ignored and
* not spent, to be safe.
* - slpUtxos: {} - UTXOs confirmed to be colored as valid SLP tokens
@@ -37,10 +51,6 @@ class UTXO {
* - groupTokens: [] - NFT Group tokens, used to create NFT tokens.
* - groupMintBatons: [] - Minting baton to create more NFT Group tokens.
*
* Note: You can pass in an optional second Boolean argument. The default
* `false` will use the normal waterfall validation method. Set to `true`,
* SLP UTXOs will be validated with the whitelist filtered SLPDB. This will
* result is many more UTXOs in the `nullUtxos` array.
*
* @apiExample Example usage:
* (async () => {
@@ -67,215 +77,235 @@ class UTXO {
* "isValid": false
* }
* ],
* "nullUtxos": [],
* "slpUtxos": {
* "type1": {
* "mintBatons": [
* {
* "height": 674512,
* "tx_hash": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "tx_pos": 2,
* "value": 546,
* "txid": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "vout": 2,
* "utxoType": "minting-baton",
* "tokenId": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "tokenTicker": "SLPTEST",
* "tokenName": "SLP Test Token",
* "tokenDocumentUrl": "https://FullStack.cash",
* "tokenDocumentHash": "",
* "decimals": 8,
* "tokenType": 1,
* "isValid": true
* }
* ],
* "tokens": [
* {
* "height": 674512,
* "tx_hash": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "tx_pos": 1,
* "value": 546,
* "txid": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "vout": 1,
* "utxoType": "token",
* "tokenQty": "100",
* "tokenId": "acbb0d3ceef55aa3e5fafc19335ae4bf2f8edba3c0567547dfd402391db32230",
* "tokenTicker": "SLPTEST",
* "tokenName": "SLP Test Token",
* "tokenDocumentUrl": "https://FullStack.cash",
* "tokenDocumentHash": "",
* "decimals": 8,
* "tokenType": 1,
* "isValid": true
* }
* ]
* },
* "nft": {
* "groupMintBatons": [
* {
* "height": 674513,
* "tx_hash": "705bcc442e5a2770e560b528f52a47b1dcc9ce9ab6a8de9dfdefa55177f00d04",
* "tx_pos": 2,
* "value": 546,
* "txid": "705bcc442e5a2770e560b528f52a47b1dcc9ce9ab6a8de9dfdefa55177f00d04",
* "vout": 2,
* "utxoType": "minting-baton",
* "transactionType": "mint",
* "tokenId": "a9a2458a0f9f0761d5b8725c256f2e7fa35b9de4dec6f47b46e9f20d92d0e395",
* "tokenType": 129,
* "tokenTicker": "NFTGT",
* "tokenName": "NFT Test Group Token",
* "tokenDocumentUrl": "https://FullStack.cash",
* "tokenDocumentHash": "",
* "decimals": 0,
* "mintBatonVout": 2,
* "isValid": true
* }
* ],
* "groupTokens": [
* {
* "height": 674513,
* "tx_hash": "705bcc442e5a2770e560b528f52a47b1dcc9ce9ab6a8de9dfdefa55177f00d04",
* "tx_pos": 1,
* "value": 546,
* "txid": "705bcc442e5a2770e560b528f52a47b1dcc9ce9ab6a8de9dfdefa55177f00d04",
* "vout": 1,
* "utxoType": "token",
* "tokenQty": "10",
* "transactionType": "mint",
* "tokenId": "a9a2458a0f9f0761d5b8725c256f2e7fa35b9de4dec6f47b46e9f20d92d0e395",
* "tokenType": 129,
* "tokenTicker": "NFTGT",
* "tokenName": "NFT Test Group Token",
* "tokenDocumentUrl": "https://FullStack.cash",
* "tokenDocumentHash": "",
* "decimals": 0,
* "mintBatonVout": 2,
* "isValid": true
* }
* ],
* "tokens": [
* {
* "height": 674512,
* "tx_hash": "eeddccc4d716f04157ea132ac93a48040fea34a6b57f3d8f0cccb7d1a731ab2b",
* "tx_pos": 1,
* "value": 546,
* "txid": "eeddccc4d716f04157ea132ac93a48040fea34a6b57f3d8f0cccb7d1a731ab2b",
* "vout": 1,
* "utxoType": "token",
* "tokenQty": "1",
* "tokenId": "eeddccc4d716f04157ea132ac93a48040fea34a6b57f3d8f0cccb7d1a731ab2b",
* "tokenTicker": "NFT004",
* "tokenName": "NFT Child",
* "tokenDocumentUrl": "https://FullStack.cash",
* "tokenDocumentHash": "",
* "decimals": 0,
* "tokenType": 65,
* "isValid": true
* }
* ]
* }
* }
* }
* ]
*
*
*/
async get (address, useWhitelist = false) {
// This version of get() uses the psf-slp-indexer. It will replace the older
// get() function that uses SLPDB.
// TODO: NFT UTXOs are identified as non-token UTXOs, which will cause a wallet
// to burn them. The psf-slp-indexer needs to be updated to mark these UTXOs.
async get (address) {
try {
// Convert address to an array if it is a string.
if (typeof address === 'string') address = [address]
if (typeof address !== 'string') {
throw new Error('address input must be a string')
}
// Throw an error if there are more than 20 addresses passed in at a time.
if (address.length > 20) throw new Error('Too many elements, 20 max.')
// Covert each address to a BCH address.
const addr = address.map(elem => this.slp.Address.toCashAddress(elem))
// Ensure the address is a BCH address.
let addr = address
if (!addr.includes('ecash')) {
addr = this.slp.Address.toCashAddress(address)
}
// Get the UTXOs associated with the address.
const utxoData = await this.electrumx.utxo(addr)
// console.log(`utxoData: ${JSON.stringify(utxoData, null, 2)}`)
const utxos = utxoData.utxos
// Hydate the utxos with token information.
let hydratedUtxos
if (useWhitelist) {
hydratedUtxos = await this.slp.Utils.hydrateUtxosWL(utxoData.utxos)
} else {
hydratedUtxos = await this.slp.Utils.hydrateUtxos(utxoData.utxos)
}
// console.log(`hydratedUtxos: ${JSON.stringify(hydratedUtxos, null, 2)}`)
let slpUtxos = []
const retAry = [] // Return array
// Get SLP UTXOs from the psf-slp-indexer
try {
const slpUtxoData = await this.psfSlpIndexer.balance(addr)
// console.log(`slpUtxoData: ${JSON.stringify(slpUtxoData, null, 2)}`)
// Loop through each address.
for (let i = 0; i < hydratedUtxos.slpUtxos.length; i++) {
const thisAddr = hydratedUtxos.slpUtxos[i]
slpUtxos = slpUtxoData.balance.utxos
} catch (err) {
// console.log('err: ', err)
const addrObj = {
address: thisAddr.address
// Exit quietly if address has no SLP UTXOs. Otherwise, throw the error.
if (err.error && !err.error.includes('Key not found in database')) {
throw err
}
// Filter out the different types of UTXOs.
addrObj.bchUtxos = thisAddr.utxos.filter(elem => elem.isValid === false)
addrObj.nullUtxos = thisAddr.utxos.filter(elem => elem.isValid === null)
// Break down the SLP UTXOs.
addrObj.slpUtxos = {
type1: {},
nft: {}
}
// Token Type 1 Minting Batons.
addrObj.slpUtxos.type1.mintBatons = thisAddr.utxos.filter(elem => {
const isValid = elem.isValid === true
const tokenTypeIs1 = elem.tokenType === 1
const isMintingBaton = elem.utxoType === 'minting-baton'
return isValid && tokenTypeIs1 && isMintingBaton
})
// Token Type 1 tokens.
addrObj.slpUtxos.type1.tokens = thisAddr.utxos.filter(elem => {
const isValid = elem.isValid === true
const tokenTypeIs1 = elem.tokenType === 1
const isToken = elem.utxoType === 'token'
return isValid && tokenTypeIs1 && isToken
})
// NFT Group Minting Batons
addrObj.slpUtxos.nft.groupMintBatons = thisAddr.utxos.filter(elem => {
const isValid = elem.isValid === true
const tokenTypeIs129 = elem.tokenType === 129
const isMintingBaton = elem.utxoType === 'minting-baton'
return isValid && tokenTypeIs129 && isMintingBaton
})
// NFT Group tokens
addrObj.slpUtxos.nft.groupTokens = thisAddr.utxos.filter(elem => {
const isValid = elem.isValid === true
const tokenTypeIs129 = elem.tokenType === 129
const isToken = elem.utxoType === 'token'
return isValid && tokenTypeIs129 && isToken
})
// NFT (Child) tokens
addrObj.slpUtxos.nft.tokens = thisAddr.utxos.filter(elem => {
const isValid = elem.isValid === true
const tokenTypeIs65 = elem.tokenType === 65
const isToken = elem.utxoType === 'token'
return isValid && tokenTypeIs65 && isToken
})
retAry.push(addrObj)
}
return retAry
// Get the sync status of the SLP indexer
const syncStatus = await this.psfSlpIndexer.status()
const slpIndexerHeight = syncStatus.status.syncedBlockHeight
const chainBlockHeight = syncStatus.status.chainBlockHeight
// Loop through the Fulcrum UTXOs.
for (let i = 0; i < utxos.length; i++) {
const thisUtxo = utxos[i]
// Loop through the UTXOs from psf-slp-indexer.
for (let j = 0; j < slpUtxos.length; j++) {
const thisSlpUtxo = slpUtxos[j]
// If the non-hydrated UTXO matches the SLP UTXO, then combine the data
// and mark the UTXO as an SLP token.
if (
thisUtxo.tx_hash === thisSlpUtxo.txid &&
thisUtxo.tx_pos === thisSlpUtxo.vout
) {
thisUtxo.txid = thisUtxo.tx_hash
thisUtxo.vout = thisUtxo.tx_pos
thisUtxo.isSlp = true
thisUtxo.type = thisSlpUtxo.type
thisUtxo.qty = thisSlpUtxo.qty
thisUtxo.tokenId = thisSlpUtxo.tokenId
thisUtxo.address = thisSlpUtxo.address
thisUtxo.tokenType = thisSlpUtxo.tokenType
break
}
}
// If there was no match, then this is a normal BCH UTXO. Mark it as such.
if (!thisUtxo.isSlp) {
thisUtxo.txid = thisUtxo.tx_hash
thisUtxo.vout = thisUtxo.tx_pos
thisUtxo.address = addr
// Check the transaction to see if its a 'null' token, ignored by
// the indexer.
const txData = await this.psfSlpIndexer.tx(thisUtxo.tx_hash)
// console.log(`txData: ${JSON.stringify(txData, null, 2)}`)
// txData.txData === undefined if the SLP indexer is syncing.
if (!txData.txData || txData.txData.isValidSlp === null) {
thisUtxo.isSlp = null
} else {
thisUtxo.isSlp = false
}
// console.log(`thisUtxo.isSlp: ${thisUtxo.isSlp}`)
// If the SLP indexer more than 1 block behind the full node, then
// move any BCH UTXOs of 600 sats or less into the null array. This
// protects token UTXOs from being burned accidentally.
if (slpIndexerHeight < chainBlockHeight - 1) {
if (thisUtxo.value < 601) {
thisUtxo.isSlp = null
}
}
}
}
// Get token UTXOs
let type1TokenUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'token' && x.tokenType === 1
)
// Hydrate the UTXOs with additional token data.
type1TokenUtxos = await this.hydrateTokenData(type1TokenUtxos)
// Collect BCH UTXOs above 1000 sats
const bchUtxos = utxos.filter(x => x.isSlp === false && x.value > 1000)
// Collect all BCH UTXOs at 1000 sats or smaller
// The prevents SLP tokens, BCMR, and other 'colored' UTXOs from being
// accidentally included into normal BCH transactions.
const infoUtxos = utxos.filter(x => x.isSlp === false && x.value <= 1000)
// Collect and hydrate any type1 baton UTXOs
let type1BatonUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'baton' && x.tokenType === 1
)
type1BatonUtxos = await this.hydrateTokenData(type1BatonUtxos)
// Collect and hydrate NFT Group tokens
let nftGroupTokenUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'token' && x.tokenType === 129
)
nftGroupTokenUtxos = await this.hydrateTokenData(nftGroupTokenUtxos)
// Collect and hydrate any Group baton UTXOs
let groupBatonUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'baton' && x.tokenType === 129
)
groupBatonUtxos = await this.hydrateTokenData(groupBatonUtxos)
// Collect and hydrate NFT child tokens
let nftChildTokenUtxos = utxos.filter(
x => x.isSlp === true && x.type === 'token' && x.tokenType === 65
)
nftChildTokenUtxos = await this.hydrateTokenData(nftChildTokenUtxos)
// Isolate any UTXOs that are marked null by the SLP indexer.
const nullUtxos = utxos.filter(x => x.isSlp === null)
const outObj = {
address: addr,
bchUtxos,
infoUtxos,
slpUtxos: {
type1: {
tokens: type1TokenUtxos,
mintBatons: type1BatonUtxos
},
group: {
tokens: nftGroupTokenUtxos,
mintBatons: groupBatonUtxos
},
nft: {
tokens: nftChildTokenUtxos
}
},
nullUtxos
}
return outObj
} catch (err) {
console.error('Error in bchjs.utxo.get()')
console.error('Error in bchjs.Utxo.get(): ', err)
if (err.error) throw new Error(err.error)
throw err
}
}
// Hydrate an array of token UTXOs with token information.
// Returns an array of token UTXOs with additional data.
async hydrateTokenData (utxoAry) {
try {
// console.log('utxoAry: ', utxoAry)
// Create a list of token IDs without duplicates.
let tokenIds = utxoAry.map(x => x.tokenId)
// Remove duplicates. https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array
tokenIds = [...new Set(tokenIds)]
// console.log('tokenIds: ', tokenIds)
// Get Genesis data for each tokenId
const genesisData = []
for (let i = 0; i < tokenIds.length; i++) {
const thisTokenId = tokenIds[i]
const thisTokenData = await this.psfSlpIndexer.tokenStats(thisTokenId)
// console.log('thisTokenData: ', thisTokenData)
genesisData.push(thisTokenData)
}
// console.log('genesisData: ', genesisData)
// Hydrate each token UTXO with data from the genesis transaction.
for (let i = 0; i < utxoAry.length; i++) {
const thisUtxo = utxoAry[i]
// Get the genesis data for this token.
const genData = genesisData.filter(
x => x.tokenData.tokenId === thisUtxo.tokenId
)
// console.log('genData: ', genData)
thisUtxo.ticker = genData[0].tokenData.ticker
thisUtxo.name = genData[0].tokenData.name
thisUtxo.documentUri = genData[0].tokenData.documentUri
thisUtxo.documentHash = genData[0].tokenData.documentHash
thisUtxo.decimals = genData[0].tokenData.decimals
if (thisUtxo.type !== 'baton') {
// Calculate the real token quantity
const qty = new BigNumber(thisUtxo.qty).dividedBy(
10 ** parseInt(thisUtxo.decimals)
)
thisUtxo.qtyStr = qty.toString()
// tokenQty is property expected by SLP.tokentype1.js library
thisUtxo.tokenQty = thisUtxo.qtyStr
}
}
return utxoAry
} catch (err) {
console.log('Error in hydrateTokenData()')
throw err
}
}
@@ -343,6 +373,57 @@ class UTXO {
return utxos[largestIndex]
}
/**
* @api Utxo.isValid() isValid()
* @apiName isValid
* @apiGroup UTXO
* @apiDescription Validate that UTXO exists and is still spendable.
*
* Given a UTXO, this method will return true if the UTXO is still in the
* mempool and still valid for spending. It will return false if the UTXO
* has been spent.
*
* @apiExample Example usage:
* (async () => {
* try {
* const utxos = await bchjs.Utxo.get('bitcoincash:qq54fgjn3hz0357n8a6guy4demw9xfkjk5jcj0xr0z');
* const isValid = bchjs.Utxo.isValid(utxos.bchUtxos[0])
* console.log(isValid);
* } catch(error) {
* console.error(error)
* }
* })()
*
* // returns
* true
*/
async isValid (utxo) {
try {
// console.log('utxo: ', utxo)
// Convert different properties from different indexers
const txid = utxo.txid || utxo.tx_hash
const vout = utxo.vout | utxo.tx_pos
// Query the full node
const txOut = await this.blockchain.getTxOut(txid, vout, true)
// console.log('txOut: ', txOut)
// Simplify results to either true or false.
let isValid = null
if (txOut === null) {
isValid = false
} else {
isValid = true
}
return isValid
} catch (err) {
console.log('Error in Utxo.isValid()')
throw err
}
}
}
module.exports = UTXO
export default UTXO
+4 -3
View File
@@ -2,10 +2,11 @@
A Mocha test file for running end-to-end (e2e) tests.
*/
// const mocha = require("mocha")
const assert = require('chai').assert
// import mocha from "mocha"
import chai from 'chai'
const sendToken = require('./send-token/send-token')
import sendToken from './send-token/send-token.js'
const { assert } = chai
describe('#end-to-end tests', () => {
describe('#send-tokens', () => {
+8 -2
View File
@@ -3,12 +3,18 @@
IPFS is working.
*/
process.env.IPFS_API = 'http://localhost:5001'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
// process.env.IPFS_API = `https://ipfs-api.fullstack.cash`
const BCHJS = require('../../../src/bch-js')
import BCHJS from '../../../src/bch-js.js'
process.env.IPFS_API = 'http://localhost:5001'
const bchjs = new BCHJS()
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
describe('#IPFS', () => {
it('should upload a file to the server', async () => {
const path = `${__dirname.toString()}/ipfs-e2e.js`
@@ -12,13 +12,14 @@
mocha --timeout=30000 anonymous-rate-limits.js
*/
const assert = require('chai').assert
import chai from 'chai'
// const RESTURL = `http://localhost:3000/v5/`
// const RESTURL = `https://abc.fullstack.cash/v4/`
const RESTURL = 'https://bchn.fullstack.cash/v4/'
// const RESTURL = `http://localhost:3000/v4/`
import BCHJS from '../../../src/bch-js.js'
const { assert } = chai
const BCHJS = require('../../../src/bch-js')
// const RESTURL = `https://abc.fullstack.cash/v5/`
const RESTURL = 'https://bchn.fullstack.cash/v5/'
const bchjs = new BCHJS({ restURL: RESTURL })
describe('#anonymous rate limits', () => {
@@ -7,15 +7,16 @@
- Update the PRO_PASS value with a current PRO_PASSES string used by bch-api.
*/
const assert = require('chai').assert
import chai from 'chai'
import BCHJS from '../../../src/bch-js.js'
const { assert } = chai
const PRO_PASS = 'testpassword'
const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`,
restURL: 'https://abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`,
// restURL: `https://bchn.fullstack.cash/v5/`,
restURL: 'https://abc.fullstack.cash/v5/',
// restURL: `http://localhost:3000/v5/`,
authPass: PRO_PASS
})
+6 -5
View File
@@ -11,15 +11,16 @@
- Update the JWT_TOKEN value with a current free-level JWT token.
*/
const assert = require('chai').assert
import chai from 'chai'
import BCHJS from '../../../src/bch-js.js'
const { assert } = chai
const JWT_TOKEN =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2YyMDIyMWMxMDAxMmFkOTQwMSIsImVtYWlsIjoiZGVtb0BkZW1vLmNvbSIsImFwaUxldmVsIjoxMCwicmF0ZUxpbWl0IjozLCJpYXQiOjE2MDQ4NTQ2OTEsImV4cCI6MTYwNzQ0NjY5MX0.iwse0z0KDKHx9graCxcOwj6lSlfKQAb1zLhmjvygvts'
const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({
restURL: 'https://api.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`,
restURL: 'https://api.fullstack.cash/v5/',
// restURL: `http://localhost:3000/v5/`,
apiToken: JWT_TOKEN
})
@@ -11,16 +11,17 @@
- Update the JWT_TOKEN value with a paid tier JWT token.
*/
const assert = require('chai').assert
import chai from 'chai'
import BCHJS from '../../../src/bch-js.js'
const { assert } = chai
const JWT_TOKEN =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M'
const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`,
restURL: 'https:/abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`,
// restURL: `https://bchn.fullstack.cash/v5/`,
restURL: 'https:/abc.fullstack.cash/v5/',
// restURL: `http://localhost:3000/v5/`,
apiToken: JWT_TOKEN
})
@@ -65,7 +66,7 @@ describe('#full node rate limits', () => {
it('should throw error for more than 100 RPM to fullnode', async () => {
try {
console.log('This test usually doesn\'t pass, because of latency.')
console.log("This test usually doesn't pass, because of latency.")
for (let i = 0; i < 100; i++) await bchjs.Control.getNetworkInfo()
} catch (err) {
// console.log(`validating after 10th call`)
+7 -6
View File
@@ -7,16 +7,17 @@
- Update the JWT_TOKEN value with a current indexer-level JWT token.
*/
const assert = require('chai').assert
import chai from 'chai'
import BCHJS from '../../../src/bch-js.js'
const { assert } = chai
const JWT_TOKEN =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M'
const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`,
restURL: 'https://abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`,
// restURL: `https://bchn.fullstack.cash/v5/`,
restURL: 'https://abc.fullstack.cash/v5/',
// restURL: `http://localhost:3000/v5/`,
apiToken: JWT_TOKEN
})
@@ -18,26 +18,33 @@ const RECV_ADDR2 = 'bchtest:qz6yw0kqgfkknfy6jh2jvlfnkzmre3lt2u0pgcckdk'
const SATOSHIS_TO_SEND = 1000
// Instantiate BITBOX.
const bitboxLib = '../../../lib/BITBOX'
const BITBOXSDK = require(bitboxLib)
const BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
// const util = require('util')
// Note: Dynamic require with variable - use dynamic import in ESM
const bitboxLib = '../../../lib/BITBOX.js'
let BITBOXSDK, BITBOX, walletInfo
// Open the wallet generated with create-wallet.
let walletInfo = {}
try {
walletInfo = require('./wallet.json')
} catch (err) {
console.log(
'Could not open wallet.json. Generate a wallet with create-wallet first.'
)
process.exit(0)
}
let SEND_ADDR, SEND_MNEMONIC
const SEND_ADDR = walletInfo.cashAddress
const SEND_MNEMONIC = walletInfo.mnemonic
// Load dependencies asynchronously
async function loadDependencies () {
BITBOXSDK = (await import(bitboxLib)).default
BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
try {
const { createRequire } = await import('module')
const require = createRequire(import.meta.url)
walletInfo = require('./wallet.json')
} catch (err) {
console.log(
'Could not open wallet.json. Generate a wallet with create-wallet first.'
)
process.exit(0)
}
SEND_ADDR = walletInfo.cashAddress
SEND_MNEMONIC = walletInfo.mnemonic
}
async function testSend () {
try {
@@ -57,7 +64,10 @@ async function testSend () {
console.log('Error in testSend: ', err)
}
}
testSend()
// Load dependencies then run test
loadDependencies().then(() => {
testSend()
})
// Build a TX hex with the largest UTXO.
async function buildTx1 (recAddr) {
@@ -17,26 +17,33 @@ const RECV_ADDR1 = 'bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05'
const SATOSHIS_TO_SEND = 1000
// Instantiate BITBOX.
const bitboxLib = '../../../lib/BITBOX'
const BITBOXSDK = require(bitboxLib)
const BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
// const util = require('util')
// Note: Dynamic require with variable - use dynamic import in ESM
const bitboxLib = '../../../lib/BITBOX.js'
let BITBOXSDK, BITBOX, walletInfo
// Open the wallet generated with create-wallet.
let walletInfo = {}
try {
walletInfo = require('./wallet.json')
} catch (err) {
console.log(
'Could not open wallet.json. Generate a wallet with create-wallet first.'
)
process.exit(0)
}
let SEND_ADDR, SEND_MNEMONIC
const SEND_ADDR = walletInfo.cashAddress
const SEND_MNEMONIC = walletInfo.mnemonic
// Load dependencies asynchronously
async function loadDependencies () {
BITBOXSDK = (await import(bitboxLib)).default
BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
try {
const { createRequire } = await import('module')
const require = createRequire(import.meta.url)
walletInfo = require('./wallet.json')
} catch (err) {
console.log(
'Could not open wallet.json. Generate a wallet with create-wallet first.'
)
process.exit(0)
}
SEND_ADDR = walletInfo.cashAddress
SEND_MNEMONIC = walletInfo.mnemonic
}
async function testSend () {
try {
@@ -54,7 +61,10 @@ async function testSend () {
console.log('Error in testSend: ', err)
}
}
testSend()
// Load dependencies then run test
loadDependencies().then(() => {
testSend()
})
// Build a TX hex with the largest UTXO.
async function buildTx1 (recAddr) {
+4 -4
View File
@@ -8,7 +8,9 @@
*/
// Inspect utility used for debugging.
const util = require('util')
import util from 'util'
import lib from '../util/e2e-util.js'
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
@@ -21,8 +23,6 @@ util.inspect.defaultOptions = {
const WALLET1 = '../wallet1.json'
const WALLET2 = '../wallet2.json'
const lib = require('../util/e2e-util')
// The main test function.
// Sends a token and reports on how long it takes to show up in SLPDB production.
async function sendTokenTest () {
@@ -95,6 +95,6 @@ function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
module.exports = {
export default {
sendTokenTest
}
+6 -3
View File
@@ -3,14 +3,14 @@
tests.
*/
module.exports = {
import SLPSDK from '../../../lib/SLP.js'
export default {
openWallet,
sendToken,
getTestTokenBalance,
threeDecimals
}
const SLPSDK = require('../../../lib/SLP')
const slpsdk = new SLPSDK()
const testTokenId =
@@ -20,6 +20,9 @@ const testTokenId =
// token balance.
async function openWallet (filename) {
try {
// Note: Dynamic imports for JSON files - use createRequire
const { createRequire } = await import('module')
const require = createRequire(import.meta.url)
const walletInfo = require(filename)
// const walletBalance = await getBalance(walletInfo)
+27
View File
@@ -0,0 +1,27 @@
/*
This test is used to interrogate the behavior of bch-js when a psf-slp-indexer
panicks and starts indexing from SLP genesis. In this corner-case, bch-js
should detect the indexer is out of sync, and protect any token UTXOs by
moving any UTXO under 600 sats into the null array.
TO RUN THIS TEST:
- Reset a local instance of psf-slp-indexer to sync from genesis.
- Start a local copy of bch-api
*/
import BCHJS from '../../../src/bch-js.js'
const bchjs = new BCHJS({
restURL: 'http://localhost:3000/v5/'
})
async function startTest () {
try {
const addr = 'bitcoincash:qzkvas58zag9tjry693mflkjze2m20ps7vx7uw7z9d'
const result = await bchjs.Utxo.get(addr)
console.log(`result: ${JSON.stringify(result, null, 2)}`)
} catch (err) {
console.error('Error in startTest(): ', err)
}
}
startTest()
+59 -12
View File
@@ -7,13 +7,13 @@
of an e2e test to be properly tested.
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
// Inspect utility used for debugging.
const util = require('util')
import util from 'util'
const assert = chai.assert
const bchjs = new BCHJS()
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
@@ -22,7 +22,7 @@ util.inspect.defaultOptions = {
describe('#blockchain', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
describe('#getBestBlockHash', () => {
@@ -103,8 +103,8 @@ describe('#blockchain', () => {
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -171,8 +171,8 @@ describe('#blockchain', () => {
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Transaction not in mempool')
assert.instanceOf(err, Error)
assert.include(err.message, 'Transaction not in mempool')
}
})
})
@@ -241,8 +241,8 @@ describe('#blockchain', () => {
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -276,6 +276,53 @@ describe('#blockchain', () => {
assert.equal(result, null)
})
})
describe('#getBlock', () => {
it('should get block information with default verbosity', async () => {
const blockhash =
'0000000000000000008e8d83cba6d45a9314bc2ef4538d4e0577c6bed8593536'
const result = await bchjs.Blockchain.getBlock(blockhash)
assert.hasAllKeys(result, [
'hash',
'confirmations',
'size',
'height',
'version',
'versionHex',
'merkleroot',
'tx',
'time',
'mediantime',
'nonce',
'bits',
'difficulty',
'chainwork',
'nTx',
'previousblockhash',
'nextblockhash'
])
assert.isArray(result.tx)
})
it('should get block information with verbosity 0', async () => {
const blockhash =
'0000000000000000008e8d83cba6d45a9314bc2ef4538d4e0577c6bed8593536'
const verbosity = 0
const result = await bchjs.Blockchain.getBlock(blockhash, verbosity)
assert.isString(result)
})
})
describe('#getBlockchainInfo', () => {
it('should get info about the blockchain', async () => {
const result = await bchjs.Blockchain.getBlockchainInfo()
// console.log(`blockchain info: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'blocks')
})
})
})
function sleep (ms) {
@@ -1,73 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
TODO
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ restURL: process.env.RESTURL })
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#rawtransaction', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
/*
Testing sentRawTransaction isn't really possible with an integration test,
as the endpoint really needs an e2e test to be properly tested. The tests
below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently.
*/
describe('sendRawTransaction', () => {
it('should send a single transaction hex', async () => {
try {
const hex =
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'bad-txns-inputs-missingorspent')
// assert.include(err.error, 'Missing inputs')
}
})
it('should send an array of tx hexes', async () => {
try {
const hexes = [
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
console.log(`result ${JSON.stringify(result, null, 2)}`)
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'bad-txns-inputs-missingorspent')
// assert.include(err.error, 'Missing inputs')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
-226
View File
@@ -1,226 +0,0 @@
/*
Integration tests for the bchjs covering SLP tokens.
These tests are specific to the ABC chain.
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../../../src/bch-js')
let bchjs
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 1
}
describe('#SLP', () => {
// before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
// })
beforeEach(async () => {
// Introduce a delay so that the BVT doesn't trip the rate limits.
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
bchjs = new BCHJS({ restURL: process.env.RESTURL })
})
describe('#util', () => {
describe('#tokenUtxoDetails', () => {
it('should handle a range of UTXO types', async () => {
const utxos = [
// Malformed SLP tx
{
note: 'Malformed SLP tx',
tx_hash:
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1,
value: 546
},
// Normal TX (non-SLP)
{
note: 'Normal TX (non-SLP)',
tx_hash:
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
tx_pos: 0,
value: 400000
},
// Valid PSF SLP tx
{
note: 'Valid PSF SLP tx',
tx_hash:
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
tx_pos: 1,
value: 546
},
// Valid SLP token not in whitelist
{
note: 'Valid SLP token not in whitelist',
tx_hash:
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1,
value: 546
},
// Token send on BCHN network.
{
note: 'Token send on BCHN network',
tx_hash:
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
tx_pos: 1,
value: 546
},
// Token send on ABC network.
{
note: 'Token send on ABC network',
tx_hash:
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
tx_pos: 1,
value: 546
},
// Known invalid SLP token send of PSF tokens.
{
note: 'Known invalid SLP token send of PSF tokens',
tx_hash:
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74',
tx_pos: 1,
value: 546
}
]
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
// Malformed SLP tx
assert.equal(data[0].tx_hash, utxos[0].tx_hash)
assert.equal(data[0].isValid, false)
// Normal TX (non-SLP)
assert.equal(data[1].tx_hash, utxos[1].tx_hash)
assert.equal(data[1].isValid, false)
// Valid PSF SLP tx
assert.equal(data[2].tx_hash, utxos[2].tx_hash)
assert.equal(data[2].isValid, true)
// Valid SLP token not in whitelist
assert.equal(data[3].tx_hash, utxos[3].tx_hash)
assert.equal(data[3].isValid, true)
// Token send on BCHN network
assert.equal(data[4].tx_hash, utxos[4].tx_hash)
// assert.equal(data[4].isValid, true)
assert.equal(data[4].isValid, null)
// Token send on ABC network
assert.equal(data[5].tx_hash, utxos[5].tx_hash)
assert.equal(data[5].isValid, true)
// Known invalid SLP token send of PSF tokens
assert.equal(data[6].tx_hash, utxos[6].tx_hash)
assert.equal(data[6].isValid, false)
})
})
describe('#validateTxid3', () => {
it('should invalidate a known invalid TXID', async () => {
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid)
assert.property(result[0], 'valid')
assert.equal(result[0].valid, null)
})
it('should validate a known valid TXID', async () => {
const txid =
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid)
assert.property(result[0], 'valid')
assert.equal(result[0].valid, true)
})
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Unprocessed SLP TX
// "a0d6406eecfd8634158efa9314ff15b4cbf451938e9dc7b5678c46b41eabc6ed" // Mint baton
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019'
]
const result = await bchjs.SLP.Utils.validateTxid3(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.equal(result[0].valid, null)
assert.equal(result[1].valid, null)
assert.equal(result[2].valid, true)
// assert.equal(result[2].valid, null)
assert.equal(result[3].valid, true)
assert.equal(result[4].valid, null)
})
})
describe('#validateTxid', () => {
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
]
const result = await bchjs.SLP.Utils.validateTxid(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.equal(result[0].valid, null)
assert.equal(result[1].valid, null)
assert.equal(result[2].valid, true)
// assert.equal(result[2].valid, null)
assert.equal(result[3].valid, true)
assert.equal(result[4].valid, null)
assert.equal(result[5].valid, true)
})
})
})
})
// Promise-based sleep function
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,38 +0,0 @@
/*
Integration tests for the utxo.js library.
*/
const assert = require('chai').assert
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS()
describe('#UTXO', () => {
beforeEach(async () => {
// sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#get', () => {
it('should get hydrated and filtered UTXOs for an address', async () => {
// const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const addr = 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'address')
assert.property(result[0], 'bchUtxos')
assert.property(result[0], 'nullUtxos')
assert.property(result[0], 'slpUtxos')
assert.isArray(result[0].bchUtxos)
assert.isArray(result[0].nullUtxos)
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,71 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
TODO
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS()
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#rawtransaction', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
/*
Testing sentRawTransaction isn't really possible with an integration test,
as the endpoint really needs an e2e test to be properly tested. The tests
below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently.
*/
describe('sendRawTransaction', () => {
it('should send a single transaction hex', async () => {
try {
const hex =
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
it('should send an array of tx hexes', async () => {
try {
const hexes = [
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
console.log(`result ${JSON.stringify(result, null, 2)}`)
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
-272
View File
@@ -1,272 +0,0 @@
/*
Integration tests for the bchjs covering SLP tokens.
These tests are specific to the ABC chain.
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../../../src/bch-js')
let bchjs
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 1
}
describe('#SLP', () => {
// before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
// })
beforeEach(async () => {
// Introduce a delay so that the BVT doesn't trip the rate limits.
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
bchjs = new BCHJS()
})
describe('#util', () => {
describe('#decodeOpReturn', () => {
it('should decode a NFT Child transaction', async () => {
const txid =
'eeddccc4d716f04157ea132ac93a48040fea34a6b57f3d8f0cccb7d1a731ab2b'
const data = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
assert.property(data, 'tokenType')
assert.property(data, 'txType')
assert.property(data, 'ticker')
assert.property(data, 'name')
assert.property(data, 'tokenId')
assert.property(data, 'documentUri')
assert.property(data, 'documentHash')
assert.property(data, 'decimals')
assert.property(data, 'mintBatonVout')
assert.property(data, 'qty')
assert.equal(data.tokenType, 65)
assert.equal(data.mintBatonVout, 0)
assert.equal(data.qty, '1')
})
})
describe('#tokenUtxoDetails', () => {
it('should handle a range of UTXO types', async () => {
const utxos = [
// Malformed SLP tx
{
note: 'Malformed SLP tx',
tx_hash:
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1,
value: 546
},
// Normal TX (non-SLP)
{
note: 'Normal TX (non-SLP)',
tx_hash:
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
tx_pos: 0,
value: 400000
},
// Valid PSF SLP tx
{
note: 'Valid PSF SLP tx',
tx_hash:
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
tx_pos: 1,
value: 546
},
// Valid SLP token not in whitelist
{
note: 'Valid SLP token not in whitelist',
tx_hash:
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1,
value: 546
},
// Token send on BCHN network.
{
note: 'Token send on BCHN network',
tx_hash:
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
tx_pos: 1,
value: 546
},
// Token send on ABC network.
{
note: 'Token send on ABC network',
tx_hash:
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
tx_pos: 1,
value: 546
},
// Known invalid SLP token send of PSF tokens.
{
note: 'Known invalid SLP token send of PSF tokens',
tx_hash:
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74',
tx_pos: 1,
value: 546
}
]
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
// Malformed SLP tx
assert.equal(data[0].tx_hash, utxos[0].tx_hash)
assert.equal(data[0].isValid, false)
// Normal TX (non-SLP)
assert.equal(data[1].tx_hash, utxos[1].tx_hash)
assert.equal(data[1].isValid, false)
// Valid PSF SLP tx
assert.equal(data[2].tx_hash, utxos[2].tx_hash)
assert.equal(data[2].isValid, true)
// Valid SLP token not in whitelist
assert.equal(data[3].tx_hash, utxos[3].tx_hash)
assert.equal(data[3].isValid, true)
// Token send on BCHN network
assert.equal(data[4].tx_hash, utxos[4].tx_hash)
assert.equal(data[4].isValid, true)
// Token send on ABC network
assert.equal(data[5].tx_hash, utxos[5].tx_hash)
assert.equal(data[5].isValid, null)
// Known invalid SLP token send of PSF tokens
assert.equal(data[6].tx_hash, utxos[6].tx_hash)
assert.equal(data[6].isValid, false)
})
})
describe('#validateTxid3', () => {
it('should invalidate a known invalid TXID', async () => {
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid)
assert.property(result[0], 'valid')
assert.equal(result[0].valid, null)
})
it('should validate a known valid TXID', async () => {
const txid =
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid)
assert.property(result[0], 'valid')
assert.equal(result[0].valid, true)
})
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Unprocessed SLP TX
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019'
]
const result = await bchjs.SLP.Utils.validateTxid3(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
// True in validateTxid() but null in validateTxid3()
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, null)
// Note: This should change from null to true once SLPDB finishes indexing.
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
})
})
describe('#validateTxid', () => {
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
]
const result = await bchjs.SLP.Utils.validateTxid(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
// True in validateTxid() but null in validateTxid3()
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, true)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, null)
})
})
})
})
// Promise-based sleep function
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,125 +0,0 @@
/*
Integration tests for the utxo.js library.
*/
const assert = require('chai').assert
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS()
describe('#UTXO', () => {
beforeEach(async () => {
// sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#get', () => {
it('should get hydrated and filtered UTXOs for an address', async () => {
// const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const addr = 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'address')
assert.property(result[0], 'bchUtxos')
assert.property(result[0], 'nullUtxos')
assert.property(result[0], 'slpUtxos')
assert.isArray(result[0].bchUtxos)
assert.isArray(result[0].nullUtxos)
})
it('should handle an array of addresses', async () => {
const addr = [
'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9',
'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
]
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'address')
assert.property(result[0], 'bchUtxos')
assert.property(result[0], 'nullUtxos')
assert.property(result[0], 'slpUtxos')
assert.isArray(result[0].bchUtxos)
assert.isArray(result[0].nullUtxos)
})
it('should handle NFTs and minting batons', async () => {
const addr = 'simpleledger:qrm0c67wwqh0w7wjxua2gdt2xggnm90xwsr5k22euj'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'address')
assert.property(result[0], 'bchUtxos')
assert.property(result[0], 'nullUtxos')
assert.property(result[0], 'slpUtxos')
assert.isArray(result[0].bchUtxos)
assert.isArray(result[0].nullUtxos)
assert.isArray(result[0].slpUtxos.type1.mintBatons)
assert.isArray(result[0].slpUtxos.type1.tokens)
assert.isArray(result[0].slpUtxos.nft.groupMintBatons)
assert.isArray(result[0].slpUtxos.nft.groupTokens)
assert.isArray(result[0].slpUtxos.nft.tokens)
})
it('should use the whitelist when flag is set', async () => {
const addr = 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9'
const useWhitelist = true
const result = await bchjs.Utxo.get(addr, useWhitelist)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'address')
assert.property(result[0], 'bchUtxos')
assert.property(result[0], 'nullUtxos')
assert.property(result[0], 'slpUtxos')
assert.isArray(result[0].bchUtxos)
assert.isArray(result[0].nullUtxos)
// Most token UTXOs should end up in the nullUtxos array.
assert.isAbove(result[0].bchUtxos.length, 0)
assert.isAbove(result[0].nullUtxos.length, 1)
})
})
describe('#findBiggestUtxo', () => {
it('should sort UTXOs from Electrumx', async () => {
const addr = 'bitcoincash:qq54fgjn3hz0357n8a6guy4demw9xfkjk5jcj0xr0z'
const electrumxUtxos = await bchjs.Electrumx.utxo(addr)
// console.log(`Electrumx utxos: ${JSON.stringify(electrumxUtxos, null, 2)}`)
const result = bchjs.Utxo.findBiggestUtxo(electrumxUtxos.utxos)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'satoshis')
assert.equal(result.satoshis, 800)
})
it('should sort UTXOs from Utxos.get()', async () => {
const addr = 'bitcoincash:qq54fgjn3hz0357n8a6guy4demw9xfkjk5jcj0xr0z'
const utxos = await bchjs.Utxo.get(addr)
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
const result = bchjs.Utxo.findBiggestUtxo(utxos[0].bchUtxos)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'satoshis')
assert.equal(result.satoshis, 800)
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,260 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
TODO
- getMempoolEntry() only works on TXs in the mempool, so it needs to be part
of an e2e test to be properly tested.
*/
const chai = require('chai')
const assert = chai.assert
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#blockchain', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#getBestBlockHash', () => {
it('should GET best block hash', async () => {
const result = await bchjs.Blockchain.getBestBlockHash()
// console.log(`result: ${util.inspect(result)}`)
assert.isString(result)
assert.equal(result.length, 64, 'Specific hash length')
})
})
describe('#getBlockHeader', () => {
it('should GET block header for a single hash', async () => {
const hash =
'000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf'
const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.hasAllKeys(result, [
'hash',
'confirmations',
'height',
'version',
'versionHex',
'merkleroot',
'time',
'mediantime',
'nonce',
'bits',
'difficulty',
'chainwork',
'previousblockhash',
'nextblockhash',
'nTx'
])
})
it('should GET block headers for an array of hashes', async () => {
const hash = [
'000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf',
'00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2'
]
const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.isArray(result)
assert.hasAllKeys(result[0], [
'hash',
'confirmations',
'height',
'version',
'versionHex',
'merkleroot',
'time',
'mediantime',
'nonce',
'bits',
'difficulty',
'chainwork',
'previousblockhash',
'nextblockhash',
'nTx'
])
})
it('should throw error on array size rate limit', async () => {
try {
const data = []
for (let i = 0; i < 25; i++) {
data.push(
'00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2'
)
}
await bchjs.Blockchain.getBlockHeader(data)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#getMempoolEntry', () => {
/*
// To run this test, the txid must be unconfirmed.
const txid =
"defea04c38ee00cf73ad402984714ed22dc0dd99b2ae5cb50d791d94343ba79b"
it(`should GET single mempool entry`, async () => {
const result = await bchjs.Blockchain.getMempoolEntry(txid)
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
"size",
"fee",
"modifiedfee",
"time",
"height",
"startingpriority",
"currentpriority",
"descendantcount",
"descendantsize",
"descendantfees",
"ancestorcount",
"ancestorsize",
"ancestorfees",
"depends"
])
})
it(`should get an array of mempool entries`, async () => {
const result = await bchjs.Blockchain.getMempoolEntry([txid, txid])
console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
"size",
"fee",
"modifiedfee",
"time",
"height",
"startingpriority",
"currentpriority",
"descendantcount",
"descendantsize",
"descendantfees",
"ancestorcount",
"ancestorsize",
"ancestorfees",
"depends"
])
})
*/
it('should throw an error if txid is not in mempool', async () => {
try {
const txid =
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
await bchjs.Blockchain.getMempoolEntry(txid)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Transaction not in mempool')
}
})
})
describe('#getTxOutProof', () => {
it('should get single tx out proof', async () => {
const txid =
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const result = await bchjs.Blockchain.getTxOutProof(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isString(result)
})
it('should get an array of tx out proofs', async () => {
const txid = [
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
]
const result = await bchjs.Blockchain.getTxOutProof(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isString(result[0])
})
})
describe('#verifyTxOutProof', () => {
const mockTxOutProof =
'00000020ac86ce8f2bda235c0dc135d18f6a777c44b121e8f41db8a51ca65000000000000cd4de3c49337712f3a1092c47c3bf73ec2f9b1cfd289ee991ede0b6eab4df229d5b8c5dffff001d82ce005b0700000003ec55d9142eac2c1d2229e5af24898b2590c111b62e2787fa1998d3d713fd432fd557124ed758fa156a6cdc6d317d5575aec2b86dfb159c62ecb4743f28bef1cb52e7a32fbec31e367ec152fdb952f75ee75bd8575f97b394093dbb0e6c694ffc0135'
it('should verify a single proof', async () => {
const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isString(result[0])
assert.equal(
result[0],
'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
)
})
it('should verify an array of proofs', async () => {
const proofs = [mockTxOutProof, mockTxOutProof]
const result = await bchjs.Blockchain.verifyTxOutProof(proofs)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isString(result[0])
assert.equal(
result[0],
'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
)
})
it('should throw error on array size rate limit', async () => {
try {
const data = []
for (let i = 0; i < 25; i++) data.push(mockTxOutProof)
const result = await bchjs.Blockchain.verifyTxOutProof(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,32 +0,0 @@
/*
Integration tests for bchjs control library.
*/
const chai = require('chai')
const assert = chai.assert
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
describe('#control', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#getNetworkInfo', () => {
it('should get info on the full node', async () => {
const result = await bchjs.Control.getNetworkInfo()
console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'version')
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,368 +0,0 @@
const chai = require('chai')
const assert = chai.assert
const sinon = require('sinon')
const util = require('util')
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
describe('#ElectrumX', () => {
let sandbox
beforeEach(async () => {
sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
afterEach(() => sandbox.restore())
describe('#utxo', () => {
it('should GET utxos for a single address', async () => {
const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'utxos')
assert.isArray(result.utxos)
assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], 'tx_hash')
assert.property(result.utxos[0], 'tx_pos')
assert.property(result.utxos[0], 'value')
})
it('should POST utxo details for an array of addresses', async () => {
const addr = [
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
]
const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'utxos')
assert.isArray(result.utxos)
assert.property(result.utxos[0], 'utxos')
assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], 'address')
assert.property(result.utxos[0].utxos[0], 'height')
assert.property(result.utxos[0].utxos[0], 'tx_hash')
assert.property(result.utxos[0].utxos[0], 'tx_pos')
assert.property(result.utxos[0].utxos[0], 'value')
})
it('should throw error on array size rate limit', async () => {
try {
const addr = []
for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
// const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${util.inspect(result)}`)
await bchjs.Electrumx.utxo(addr)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#balance', () => {
it('should GET balance for a single address', async () => {
const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'balance')
assert.property(result.balance, 'confirmed')
assert.property(result.balance, 'unconfirmed')
})
it('should POST request for balances for an array of addresses', async () => {
const addr = [
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
]
const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'balances')
assert.isArray(result.balances)
assert.property(result.balances[0], 'address')
assert.property(result.balances[0], 'balance')
assert.property(result.balances[0].balance, 'confirmed')
assert.property(result.balances[0].balance, 'unconfirmed')
})
it('should throw error on array size rate limit', async () => {
try {
const addr = []
for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
const result = await bchjs.Electrumx.balance(addr)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#transactions', () => {
it('should GET transaction history for a single address', async () => {
const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'transactions')
assert.isArray(result.transactions)
assert.property(result.transactions[0], 'height')
assert.property(result.transactions[0], 'tx_hash')
})
it('should POST request for transaction history for an array of addresses', async () => {
const addr = [
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
]
const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'transactions')
assert.isArray(result.transactions)
assert.property(result.transactions[0], 'address')
assert.property(result.transactions[0], 'transactions')
assert.isArray(result.transactions[0].transactions)
assert.property(result.transactions[0].transactions[0], 'height')
assert.property(result.transactions[0].transactions[0], 'tx_hash')
})
it('should throw error on array size rate limit', async () => {
try {
const addr = []
for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
const result = await bchjs.Electrumx.transactions(addr)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#unconfirmed', () => {
// These tests won't work because unconfirmed transactions are transient in nature.
/*
it(`should GET unconfirmed UTXOs (mempool) for a single address`, async () => {
const addr = "bchtest:qp25k20dgcljrz4hkdz43partam3j5httyprjp23qd"
const result = await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success")
assert.equal(result.success, true)
assert.property(result, "utxos")
assert.isArray(result.utxos)
assert.property(result.utxos[0], "height")
assert.property(result.utxos[0], "tx_hash")
assert.property(result.utxos[0], "fee")
})
it(`should POST unconfirmed UTXO details for an array of addresses`, async () => {
const addr = [
"bchtest:qp25k20dgcljrz4hkdz43partam3j5httyprjp23qd",
"bchtest:qpkl3xylrjx4jup6m66e7zg7whlaucsxeudxeqawdj"
]
const result = await bchjs.Electrumx.unconfirmed(addr)
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success")
assert.equal(result.success, true)
assert.property(result, "utxos")
assert.isArray(result.utxos)
assert.property(result.utxos[0], "utxos")
assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], "address")
assert.property(result.utxos[0].utxos[0], "height")
assert.property(result.utxos[0].utxos[0], "tx_hash")
assert.property(result.utxos[0].utxos[0], "fee")
})
*/
it('should throw error on array size rate limit', async () => {
try {
const addr = []
for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#blockHeader', () => {
it('should GET block headers for given height and count', async () => {
const height = 42
const count = 2
const result = await bchjs.Electrumx.blockHeader(height, count)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'headers')
assert.isArray(result.headers)
assert.equal(result.headers.length, 2)
})
it('should GET block headers for given height with default count = 1', async () => {
const height = 42
const result = await bchjs.Electrumx.blockHeader(height)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'headers')
assert.isArray(result.headers)
assert.equal(result.headers.length, 1)
})
})
describe('#txData', () => {
it('should GET details for a single transaction', async () => {
const txid =
'76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
const result = await bchjs.Electrumx.txData(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'details')
assert.isObject(result.details)
assert.property(result.details, 'blockhash')
assert.property(result.details, 'hash')
assert.property(result.details, 'hex')
assert.property(result.details, 'vin')
assert.property(result.details, 'vout')
assert.equal(result.details.hash, txid)
})
it('should POST details for an array of transactions', async () => {
const txids = [
'76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee',
'76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
]
const result = await bchjs.Electrumx.txData(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'transactions')
assert.isArray(result.transactions)
assert.property(result.transactions[0], 'txid')
assert.property(result.transactions[0], 'details')
assert.property(result.transactions[0].details, 'blockhash')
assert.property(result.transactions[0].details, 'hash')
assert.property(result.transactions[0].details, 'hex')
assert.property(result.transactions[0].details, 'vin')
assert.property(result.transactions[0].details, 'vout')
})
it('should throw error on array size rate limit', async () => {
try {
const txids = []
for (let i = 0; i < 25; i++) {
txids.push(
'76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
)
}
await bchjs.Electrumx.txData(txids)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#broadcast', () => {
it('should broadcast a single transaction', async () => {
const txHex =
'020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000'
try {
await bchjs.Electrumx.broadcast(txHex)
} catch (err) {
assert.property(err, 'success')
assert.equal(err.success, false)
assert.include(
err.error,
'the transaction was rejected by network rules'
)
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
-147
View File
@@ -1,147 +0,0 @@
const chai = require('chai')
const assert = chai.assert
const sinon = require('sinon')
const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ ninsightURL: 'https://trest.bitcoin.com/v2' })
describe('#Ninsight', () => {
let sandbox
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
sandbox = sinon.createSandbox()
})
afterEach(() => sandbox.restore())
describe('#utxo', () => {
it('should GET utxos for a single address', async () => {
const addr = 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr'
const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result[0], 'utxos')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'slpAddress')
assert.property(result[0], 'scriptPubKey')
assert.property(result[0], 'asm')
assert.isArray(result[0].utxos)
assert.property(result[0].utxos[0], 'txid')
assert.property(result[0].utxos[0], 'vout')
assert.property(result[0].utxos[0], 'amount')
assert.property(result[0].utxos[0], 'satoshis')
assert.property(result[0].utxos[0], 'height')
assert.property(result[0].utxos[0], 'confirmations')
})
it('should POST utxo details for an array of addresses', async () => {
const addr = [
'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr',
'bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul'
]
const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isArray(result[0].utxos)
assert.property(result[0], 'utxos')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'slpAddress')
assert.property(result[0], 'scriptPubKey')
assert.property(result[0], 'asm')
// assert.hasAnyKeys(result[0][0], [
// "txid",
// "vout",
// "value",
// "height",
// "confirmations"
// ])
})
})
describe('#transactions', () => {
it('should POST transactions history for a single address', async () => {
const addr = 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr'
const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'txs')
assert.isArray(result[0].txs)
assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], 'vout')
})
it('should POST transactions history for an array of addresses', async () => {
const addr = [
'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr',
'bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul'
]
const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'txs')
assert.isArray(result[0].txs)
assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], 'vout')
})
})
describe('#txDetails', () => {
it('should POST transactions details for a single address', async () => {
const txid =
'76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea'
const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.property(result[0], 'version')
assert.property(result[0], 'locktime')
assert.property(result[0], 'vin')
assert.property(result[0], 'vout')
assert.property(result[0], 'blockhash')
assert.property(result[0], 'blockheight')
assert.property(result[0], 'confirmations')
assert.property(result[0], 'time')
assert.property(result[0], 'blocktime')
assert.property(result[0], 'valueOut')
assert.property(result[0], 'size')
})
it('should POST transactions details for an array of addresses', async () => {
const txid = [
'f191d1062789d7071da6f2168ba306869a829294f6b1c09d03492db4ca3a8e77',
'76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea'
]
const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.property(result[0], 'vin')
assert.property(result[0], 'vout')
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,296 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
TODO
*/
const chai = require('chai')
const assert = chai.assert
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#rawtransaction', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#decodeRawTransaction', () => {
it('should decode tx for a single hex', async () => {
const hex =
'0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
const result = await bchjs.RawTransactions.decodeRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
'txid',
'hash',
'size',
'version',
'locktime',
'vin',
'vout'
])
assert.isArray(result.vin)
assert.isArray(result.vout)
})
it('should decode an array of tx hexes', async () => {
const hexes = [
'0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000',
'0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
]
const result = await bchjs.RawTransactions.decodeRawTransaction(hexes)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
'txid',
'hash',
'size',
'version',
'locktime',
'vin',
'vout'
])
assert.isArray(result[0].vin)
assert.isArray(result[0].vout)
})
it('should throw error on array size rate limit', async () => {
try {
const data = []
for (let i = 0; i < 25; i++) {
data.push(
'0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
)
}
const result = await bchjs.RawTransactions.decodeRawTransaction(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#getRawTransaction', () => {
it('should decode a single txid, with concise output', async () => {
const txid =
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const verbose = false
const result = await bchjs.RawTransactions.getRawTransaction(
txid,
verbose
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isString(result)
})
it('should decode a single txid, with verbose output', async () => {
const txid =
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const verbose = true
const result = await bchjs.RawTransactions.getRawTransaction(
txid,
verbose
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
'hex',
'txid',
'hash',
'size',
'version',
'locktime',
'vin',
'vout',
'blockhash',
'confirmations',
'time',
'blocktime'
])
assert.isArray(result.vin)
assert.isArray(result.vout)
})
it('should decode an array of txids, with a concise output', async () => {
const txid = [
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
]
const verbose = false
const result = await bchjs.RawTransactions.getRawTransaction(
txid,
verbose
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isString(result[0])
})
it('should decode an array of txids, with a verbose output', async () => {
const txid = [
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
]
const verbose = true
const result = await bchjs.RawTransactions.getRawTransaction(
txid,
verbose
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
'hex',
'txid',
'hash',
'size',
'version',
'locktime',
'vin',
'vout',
'blockhash',
'confirmations',
'time',
'blocktime'
])
assert.isArray(result[0].vin)
assert.isArray(result[0].vout)
})
it('should throw error on array size limit', async () => {
try {
const dataMock =
'1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const data = []
for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.getRawTransaction(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
describe('#decodeScript', () => {
it('should decode script for a single hex', async () => {
const hex =
'4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16'
const result = await bchjs.RawTransactions.decodeScript(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['asm', 'type', 'p2sh'])
})
// CT 2/20/19 - Waiting for this PR to be merged complete the test:
// https://github.com/Bitcoin-com/rest.bitcoin.com/pull/312
/*
it("should decode an array of tx hexes", async () => {
const hexes = [
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16",
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
]
const result = await bchjs.RawTransactions.decodeScript(hexes)
console.log(`result ${JSON.stringify(result, null, 2)}`)
})
*/
})
/*
Testing sentRawTransaction isn't really possible with an integration test,
as the endpoint really needs an e2e test to be properly tested. The tests
below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently.
*/
describe('sendRawTransaction', () => {
it('should send a single transaction hex', async () => {
try {
const hex =
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
it('should send an array of tx hexes', async () => {
try {
const hexes = [
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
console.log(`result ${JSON.stringify(result, null, 2)}`)
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
it('should throw error on array size rate limit', async () => {
try {
const dataMock =
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
const data = []
for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.sendRawTransaction(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
-172
View File
@@ -1,172 +0,0 @@
/*
Integration tests for the bchjs covering SLP tokens.
*/
const chai = require('chai')
const assert = chai.assert
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 1
}
describe('#SLP', () => {
beforeEach(async () => {
// Introduce a delay so that the BVT doesn't trip the rate limits.
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#util', () => {
it('should get information on the Oasis token', async () => {
const tokenId =
'a371e9934c7695d08a5eb7f31d3bceb4f3644860cc67520cda1e149423b9ec39'
const result = await bchjs.SLP.Utils.list(tokenId)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
'decimals',
'timestamp',
'timestamp_unix',
'versionType',
'documentUri',
'symbol',
'name',
'containsBaton',
'id',
'documentHash',
'initialTokenQty',
'blockCreated',
'blockLastActiveSend',
'blockLastActiveMint',
'txnsSinceGenesis',
'validAddress',
'totalMinted',
'totalBurned',
'circulatingSupply',
'mintingBatonStatus'
])
})
})
describe('#decodeOpReturn', () => {
it('should decode the OP_RETURN for a SEND txid', async () => {
const txid =
'ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1'
const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['amounts', 'tokenType', 'tokenId', 'txType'])
})
})
describe('#balancesForAddress', () => {
it('should fetch all balances for address: slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9', async () => {
const balances = await bchjs.SLP.Utils.balancesForAddress(
'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
)
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
assert.isArray(balances)
assert.hasAllKeys(balances[0], [
'tokenId',
'balanceString',
'balance',
'decimalCount',
'slpAddress'
])
})
it('should fetch balances for multiple addresses', async () => {
const addresses = [
'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9',
'slptest:qr5uy4h8ysyhwkp9s245scckdnc7teyjqc5ft2z43h'
]
const balances = await bchjs.SLP.Utils.balancesForAddress(addresses)
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
assert.isArray(balances)
assert.isArray(balances[0])
assert.hasAllKeys(balances[0][0], [
'tokenId',
'balanceString',
'balance',
'decimalCount',
'slpAddress'
])
})
})
describe('#tokenUtxoDetails', () => {
it('should hydrate UTXOs', async () => {
const bchAddr = bchjs.SLP.Address.toCashAddress(
'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
)
const utxos = await bchjs.Electrumx.utxo([bchAddr])
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
const utxoInfo = await bchjs.SLP.Utils.tokenUtxoDetails(
utxos.utxos[0].utxos
)
// console.log(`utxoInfo: ${JSON.stringify(utxoInfo, null, 2)}`)
assert.isArray(utxoInfo)
// first UTXO should be a PSF test token.
assert.equal(utxoInfo[0].isValid, true)
})
})
describe('#hydrateUtxos', () => {
// This test will error out if the LOCAL_RESTURL settings is not set properly
// in bch-api.
it('should hydrate UTXOs', async () => {
const bchAddr = bchjs.SLP.Address.toCashAddress(
'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
)
const utxos = await bchjs.Electrumx.utxo([bchAddr])
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
const utxoInfo = await bchjs.SLP.Utils.hydrateUtxos(utxos.utxos)
// console.log(`utxoInfo: ${JSON.stringify(utxoInfo, null, 2)}`)
assert.isArray(utxoInfo.slpUtxos[0].utxos)
// first UTXO should be a PSF test token.
assert.equal(utxoInfo.slpUtxos[0].utxos[0].isValid, true)
})
})
describe('#validateTxid2', () => {
it('should validate a token txid', async () => {
const txid =
'ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1'
const validated = await bchjs.SLP.Utils.validateTxid(txid)
// console.log(validated)
assert.equal(validated[0].valid, true)
})
})
})
// Promise-based sleep function
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@@ -1,9 +0,0 @@
#!/bin/bash
export RESTURL=https://free-test.fullstack.cash/v4/
export NETWORK=testnet
export IS_USING_FREE_TIER=true
cd test/integration/testnet/
mocha --timeout 30000 blockchain.js control.js electrumx.js rawtransaction.js slp.js util.js
#mocha --timeout 30000 blockchain.js
-109
View File
@@ -1,109 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
*/
const chai = require('chai')
const assert = chai.assert
const RESTURL = process.env.RESTURL
? process.env.RESTURL
: 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#util', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#validateAddress', () => {
it('should return false for testnet addr on mainnet', async () => {
const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peu'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false)
})
it('should return false for bad address', async () => {
const address = 'bchtest:qqqk4y6lsl5da64sg53xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false)
})
it('should validate valid address', async () => {
const address = 'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
'isvalid',
'address',
'scriptPubKey',
// "ismine",
// "iswatchonly",
'isscript'
])
assert.equal(result.isvalid, true)
})
it('should validate an array of addresses', async () => {
const address = [
'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y',
'bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh'
]
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
'isvalid',
'address',
'scriptPubKey',
// "ismine",
// "iswatchonly",
'isscript'
])
})
it('should throw error on array size rate limit', async () => {
try {
const dataMock = 'bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh'
const data = []
for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.Util.validateAddress(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+4 -4
View File
@@ -2,20 +2,20 @@
Integration tests for bchjs control library.
*/
const chai = require('chai')
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
const assert = chai.assert
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
describe('#control', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
describe('#getNetworkInfo', () => {
it('should get info on the full node', async () => {
const result = await bchjs.Control.getNetworkInfo()
console.log(`result: ${JSON.stringify(result, null, 2)}`)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'version')
})
+29
View File
@@ -0,0 +1,29 @@
/*
Integration tests for bchjs dsproof library.
*/
// Global npm libraries
import chai from 'chai'
// Local libraries
import BCHJS from '../../src/bch-js.js'
const { assert } = chai
const bchjs = new BCHJS()
describe('#DSProof', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await bchjs.Util.sleep(1000)
})
describe('#getDSProof', () => {
it('should get TX info from the full node', async () => {
const txid =
'ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e'
const result = await bchjs.DSProof.getDSProof(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result, null)
})
})
})
+20 -18
View File
@@ -1,8 +1,8 @@
const chai = require('chai')
const assert = chai.assert
const sinon = require('sinon')
import chai from 'chai'
import sinon from 'sinon'
const BCHJS = require('../../src/bch-js')
import BCHJS from '../../src/bch-js.js'
const assert = chai.assert
const bchjs = new BCHJS()
describe('#ElectrumX', () => {
@@ -11,7 +11,7 @@ describe('#ElectrumX', () => {
beforeEach(async () => {
sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
afterEach(() => sandbox.restore())
@@ -73,8 +73,8 @@ describe('#ElectrumX', () => {
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -129,8 +129,8 @@ describe('#ElectrumX', () => {
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -187,8 +187,8 @@ describe('#ElectrumX', () => {
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -250,8 +250,8 @@ describe('#ElectrumX', () => {
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -345,8 +345,8 @@ describe('#ElectrumX', () => {
// console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.instanceOf(err, Error)
assert.include(err.message, 'Array too large')
}
})
})
@@ -359,10 +359,9 @@ describe('#ElectrumX', () => {
try {
await bchjs.Electrumx.broadcast(txHex)
} catch (err) {
assert.property(err, 'success')
assert.equal(err.success, false)
// console.error('err: ', err)
assert.include(
err.error,
err.message,
'the transaction was rejected by network rules'
)
}
@@ -371,6 +370,9 @@ describe('#ElectrumX', () => {
describe('#sortAllTxs', () => {
it('should GET transaction history for a single address', async () => {
// Add delay for this endpoint.
await sleep(6000)
const addr = 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
const txs = await bchjs.Electrumx.transactions(addr)
+13 -4
View File
@@ -1,15 +1,20 @@
const assert = require('chai').assert
// const assert = require('chai').assert
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
// const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS()
describe('#Encryption', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
describe('#getPubKey', () => {
// Commenting out these tests since they are failing in BVT due to 429 errors
/*
it('should get a public key', async () => {
// Add delay for this endpoint.
await sleep(8000)
const addr = 'bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq'
const result = await bchjs.encryption.getPubKey(addr)
@@ -21,6 +26,9 @@ describe('#Encryption', () => {
})
it('should report when public key can not be found', async () => {
// Add delay for this endpoint.
await sleep(8000)
const addr = 'bitcoincash:qrgqqkky28jdkv3w0ctrah0mz3jcsnsklc34gtukrh'
const result = await bchjs.encryption.getPubKey(addr)
@@ -31,6 +39,7 @@ describe('#Encryption', () => {
assert.property(result, 'publicKey')
assert.equal(result.publicKey, 'not found')
})
*/
})
})
-138
View File
@@ -1,138 +0,0 @@
const chai = require('chai')
const assert = chai.assert
const sinon = require('sinon')
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS({ ninsightURL: 'https://rest.bitcoin.com/v2' })
describe('#Ninsight', () => {
let sandbox
beforeEach(async () => {
sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
afterEach(() => sandbox.restore())
describe('#utxo', () => {
it('should GET utxos for a single address', async () => {
const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result[0], 'utxos')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'slpAddress')
assert.property(result[0], 'scriptPubKey')
assert.property(result[0], 'asm')
assert.isArray(result[0].utxos)
assert.property(result[0].utxos[0], 'txid')
assert.property(result[0].utxos[0], 'vout')
assert.property(result[0].utxos[0], 'amount')
assert.property(result[0].utxos[0], 'satoshis')
assert.property(result[0].utxos[0], 'height')
assert.property(result[0].utxos[0], 'confirmations')
})
it('should POST utxo details for an array of addresses', async () => {
const addr = [
'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
]
const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.isArray(result[0].utxos)
assert.property(result[0], 'utxos')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'slpAddress')
assert.property(result[0], 'scriptPubKey')
assert.property(result[0], 'asm')
})
})
describe('#transactions', () => {
it('should POST transactions history for a single address', async () => {
const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'txs')
assert.isArray(result[0].txs)
assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], 'vout')
})
it('should POST transactions history for an array of addresses', async () => {
const addr = [
'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
]
const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'cashAddress')
assert.property(result[0], 'legacyAddress')
assert.property(result[0], 'txs')
assert.isArray(result[0].txs)
assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], 'vout')
})
})
describe('#txDetails', () => {
it('should POST transactions details for a single address', async () => {
const txid = 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'
const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.property(result[0], 'version')
assert.property(result[0], 'locktime')
assert.property(result[0], 'vin')
assert.property(result[0], 'vout')
assert.property(result[0], 'blockhash')
assert.property(result[0], 'blockheight')
assert.property(result[0], 'confirmations')
assert.property(result[0], 'time')
assert.property(result[0], 'blocktime')
assert.property(result[0], 'valueOut')
assert.property(result[0], 'size')
})
it('should POST transactions details for an array of addresses', async () => {
const txid = [
'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
'4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
]
const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.property(result[0], 'txid')
assert.property(result[0], 'vin')
assert.property(result[0], 'vout')
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+8 -34
View File
@@ -1,38 +1,13 @@
const assert = require('chai').assert
const BCHJS = require('../../src/bch-js')
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
const { assert } = chai
const bchjs = new BCHJS()
describe('#price', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
describe('#current', () => {
describe('#single currency', () => {
it('should get current price for single currency', async () => {
const result = await bchjs.Price.current('usd')
assert.notEqual(0, result)
})
})
})
describe('#getUsd', () => {
it('should get the USD price of BCH', async () => {
const result = await bchjs.Price.getUsd()
// console.log(result)
assert.isNumber(result)
})
})
describe('#getBchaUsd', () => {
it('should get the USD price of BCHA', async () => {
const result = await bchjs.Price.getBchaUsd()
console.log(result)
assert.isNumber(result)
})
})
describe('#getBchUsd', () => {
it('should get the USD price of BCH', async () => {
const result = await bchjs.Price.getBchUsd()
@@ -42,13 +17,12 @@ describe('#price', () => {
})
})
describe('#rates', () => {
it('should get the price of BCH in several currencies', async () => {
const result = await bchjs.Price.rates()
describe('#getPsffppPrice', () => {
it('should get the price to write 1MB to the PSFFPP', async () => {
const result = await bchjs.Price.getPsffppPrice()
// console.log(result)
assert.property(result, 'USD')
assert.property(result, 'CAD')
assert.isNumber(result)
})
})
})
@@ -0,0 +1,185 @@
/*
Integration tests for the psf-slp-indexer.js library, specific to the BCH
blockchain.
*/
// Global npm libraries
import chai from 'chai'
// Local libraries
import BCHJS from '../../src/bch-js.js'
const { assert } = chai
let bchjs
describe('#psf-slp-indexer', () => {
beforeEach(async () => {
// Introduce a delay so that the BVT doesn't trip the rate limits.
if (process.env.IS_USING_FREE_TIER) await sleep(3000)
bchjs = new BCHJS()
})
describe('#status', () => {
it('should return the status of the indexer.', async () => {
const result = await bchjs.PsfSlpIndexer.status()
// console.log('result: ', result)
assert.property(result.status, 'startBlockHeight')
assert.property(result.status, 'syncedBlockHeight')
assert.property(result.status, 'chainBlockHeight')
})
})
describe('#balance', () => {
it('should get balance data for an address.', async () => {
const addr = 'bitcoincash:qzmd5vxgh9m22m6fgvm57yd6kjnjl9qnwywsf3583n'
const result = await bchjs.PsfSlpIndexer.balance(addr)
// console.log('result: ', result)
assert.property(result.balance, 'utxos')
assert.property(result.balance, 'txs')
assert.property(result.balance, 'balances')
})
})
describe('#tokenStats', () => {
it('should get stats on a token, without tx history', async () => {
const tokenId =
'38e97c5d7d3585a2cbf3f9580c82ca33985f9cb0845d4dcce220cb709f9538b0'
const result = await bchjs.PsfSlpIndexer.tokenStats(tokenId)
// console.log('result: ', result)
assert.property(result.tokenData, 'documentUri')
assert.property(result.tokenData, 'totalBurned')
})
it('should get stats on a token, with tx history', async () => {
const tokenId =
'38e97c5d7d3585a2cbf3f9580c82ca33985f9cb0845d4dcce220cb709f9538b0'
const result = await bchjs.PsfSlpIndexer.tokenStats(tokenId, true)
// console.log('result: ', result)
assert.property(result.tokenData, 'documentUri')
assert.property(result.tokenData, 'txs')
assert.property(result.tokenData, 'totalBurned')
})
})
describe('#tx', () => {
it('should get hydrated tx data for an SLP transaction', async () => {
const txid =
'947ccb2a0d62ca287bc4b0993874ab0f9f6afd454193e631e2bf84dca66731fc'
const result = await bchjs.PsfSlpIndexer.tx(txid)
// console.log('result: ', result)
assert.property(result.txData, 'vin')
assert.property(result.txData, 'vout')
assert.property(result.txData, 'isValidSlp')
assert.equal(result.txData.isValidSlp, true)
})
it('should mark non-SLP transaction as false', async () => {
const txid =
'03d6e6b63647ce7b02ecc73dc6d41b485be14a3e20eed4474b8a840358ddf14e'
const result = await bchjs.PsfSlpIndexer.tx(txid)
// console.log('result: ', result)
assert.property(result.txData, 'vin')
assert.property(result.txData, 'vout')
assert.property(result.txData, 'isValidSlp')
assert.equal(result.txData.isValidSlp, false)
})
// FlexUSD transactions
// FlexUSD is blacklisted by the SLP indexer.
it('should mark blacklisted token as null', async () => {
const txid =
'302113c11b90edc5f36c073d2f8a75e1e0eaf59b56235491a843d3819cd6a85f'
const result = await bchjs.PsfSlpIndexer.tx(txid)
// console.log('result: ', result)
assert.property(result.txData, 'vin')
assert.property(result.txData, 'vout')
assert.property(result.txData, 'isValidSlp')
assert.equal(result.txData.isValidSlp, false)
})
it('should throw error for non-existent txid', async () => {
try {
const txid =
'302113c11b90edc5f36c073d2f8a75e1e0eaf59b56235491a843d3819cd6a85e'
await bchjs.PsfSlpIndexer.tx(txid)
// console.log('result: ', result)
assert.fail('Unexpected code path')
} catch (err) {
// console.log(err)
assert.include(err.message, 'No such mempool or blockchain transaction')
}
})
})
describe('#getTokenData', () => {
it('should get token data', async () => {
const tokenId =
'd9aafa7acb514c597caf440ae268b5e4e955f2687e05f044cdf8fd9550d9a27b'
// bchjs.PsfSlpIndexer.restURL = 'http://localhost:3000/v5/'
const result = await bchjs.PsfSlpIndexer.getTokenData(tokenId)
// console.log('result: ', result)
assert.property(result, 'genesisData')
assert.property(result, 'immutableData')
assert.property(result, 'mutableData')
assert.isObject(result.genesisData)
assert.isString(result.immutableData)
assert.isString(result.mutableData)
})
it('should get token data with a transaction history', async () => {
const tokenId = '43eddfb11c9941edffb8c8815574bb0a43969a7b1de39ad14cd043eaa24fd38d'
const result = await bchjs.PsfSlpIndexer.getTokenData(tokenId, true)
// console.log('result: ', result)
assert.isArray(result.genesisData.txs)
})
})
// This test is commented out because it can not succeed in the BVT without
// tripping rate limits.
// describe('#getTokenData2', () => {
// it('should get token data', async () => {
// const tokenId =
// 'd9aafa7acb514c597caf440ae268b5e4e955f2687e05f044cdf8fd9550d9a27b'
//
// // bchjs.PsfSlpIndexer.restURL = 'http://localhost:3000/v5/'
// const result = await bchjs.PsfSlpIndexer.getTokenData2(tokenId)
// // console.log('result: ', result)
//
// assert.property(result, 'tokenStats')
// assert.property(result, 'mutableData')
// assert.property(result, 'immutableData')
// assert.property(result, 'tokenIcon')
// assert.property(result, 'fullSizedUrl')
// assert.property(result, 'optimizedTokenIcon')
// assert.property(result, 'optimizedFullSizedUrl')
// assert.property(result, 'iconRepoCompatible')
// assert.property(result, 'ps002Compatible')
// })
// })
})
// Promise-based sleep function
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+78 -37
View File
@@ -1,17 +1,16 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
Integration tests for the bchjs.
TODO
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
// Inspect utility used for debugging.
const util = require('util')
import util from 'util'
const assert = chai.assert
const bchjs = new BCHJS()
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
@@ -20,7 +19,7 @@ util.inspect.defaultOptions = {
describe('#rawtransaction', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
if (process.env.IS_USING_FREE_TIER) await sleep(1500)
})
describe('#decodeRawTransaction', () => {
@@ -192,8 +191,7 @@ describe('#rawtransaction', () => {
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
assert.include(err.message, 'Array too large')
}
})
})
@@ -206,7 +204,9 @@ describe('#rawtransaction', () => {
const result = await bchjs.RawTransactions.decodeScript(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['asm', 'type', 'p2sh'])
assert.property(result, 'asm')
assert.property(result, 'type')
assert.property(result, 'p2sh')
})
// CT 2/20/19 - Waiting for this PR to be merged complete the test:
@@ -231,6 +231,40 @@ describe('#rawtransaction', () => {
that the server is responding on those endpoints, and responds consistently.
*/
describe('#sendRawTransaction', () => {
it('should send a single transaction hex', async () => {
try {
const hex =
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
it('should send an array of tx hexes', async () => {
try {
const hexes = [
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
'01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
console.log(`result ${JSON.stringify(result, null, 2)}`)
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ['error'])
assert.include(err.error, 'Missing inputs')
}
})
it('should throw error on array size rate limit', async () => {
try {
const dataMock =
@@ -252,9 +286,13 @@ describe('#rawtransaction', () => {
describe('#_getInputAddrs', () => {
it('should return an array of input addresses', async () => {
// const txid = '32233db13f2ae6d82b6262f335643dccf09fc0bcfcef4bc3fbe023355f02e112'
const txid = '05f7d4a4e25f53d63a360434eb54f221abf159112b7fffc91da1072a079cded3'
const txid =
'05f7d4a4e25f53d63a360434eb54f221abf159112b7fffc91da1072a079cded3'
const txDetails = await bchjs.RawTransactions.getRawTransaction(txid, true)
const txDetails = await bchjs.RawTransactions.getRawTransaction(
txid,
true
)
const result = await bchjs.RawTransactions._getInputAddrs(txDetails)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -263,43 +301,46 @@ describe('#rawtransaction', () => {
assert.equal(result.length, 1)
assert.property(result[0], 'vin')
assert.property(result[0], 'address')
assert.property(result[0], 'value')
})
})
describe('#getTxData', () => {
it('should return tx data with input addresses', async () => {
const txid = '05f7d4a4e25f53d63a360434eb54f221abf159112b7fffc91da1072a079cded3'
const txid =
'05f7d4a4e25f53d63a360434eb54f221abf159112b7fffc91da1072a079cded3'
const result = await bchjs.RawTransactions.getTxData(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result.vin[0], 'address')
assert.property(result.vin[0], 'value')
})
})
describe('#getTxDataSlp', () => {
it('should return tx data with SLP information', async () => {
const txid = 'b438855cfcab64516b44097d7212df9cdb99226c8d7c7ab504d35fcfd834cb5b'
const result = await bchjs.RawTransactions.getTxDataSlp(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result.vin[0], 'address')
assert.property(result.vin[0], 'tokenQty')
assert.equal(result.vin[0].tokenQty, null)
assert.equal(result.vin[1].tokenQty, '100000000000')
})
it('should handle non-slp tx', async () => {
const txid = '04a6aca328af2445327015895b8da9766093b1989b52e477559759eb8072fc0a'
const result = await bchjs.RawTransactions.getTxDataSlp(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result, false)
})
})
// describe('#getTxDataSlp', () => {
// it('should return tx data with SLP information', async () => {
// const txid = 'b438855cfcab64516b44097d7212df9cdb99226c8d7c7ab504d35fcfd834cb5b'
//
// const result = await bchjs.RawTransactions.getTxDataSlp(txid)
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
//
// assert.property(result.vin[0], 'address')
// assert.property(result.vin[0], 'tokenQty')
//
// assert.equal(result.vin[0].tokenQty, null)
// assert.equal(result.vin[1].tokenQty, '100000000000')
// })
//
// it('should handle non-slp tx', async () => {
// const txid = '04a6aca328af2445327015895b8da9766093b1989b52e477559759eb8072fc0a'
//
// const result = await bchjs.RawTransactions.getTxDataSlp(txid)
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
//
// assert.equal(result, false)
// })
// })
})
function sleep (ms) {
+607 -929
View File
File diff suppressed because it is too large Load Diff
+109
View File
@@ -0,0 +1,109 @@
/*
Integration tests for the transaction.js library.
*/
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
const { assert } = chai
const bchjs = new BCHJS()
describe('#Transaction', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await bchjs.Util.sleep(1000)
})
describe('#get', () => {
it('should get a tx details for a non-SLP TX with an OP_RETURN', async () => {
const txid =
'01517ff1587fa5ffe6f5eb91c99cf3f2d22330cd7ee847e928ce90ca95bf781b'
const result = await bchjs.Transaction.get(txid)
// console.log('result: ', result)
assert.property(result.txData, 'txid')
assert.property(result.txData, 'vin')
assert.property(result.txData, 'vout')
assert.equal(result.txData.isValidSlp, false)
})
it('should handle a coinbase transaction', async () => {
const txid = 'cca1d2dd3a533d2f501448dec03face2cb2814afd59a533a611e9a2909f2302b'
const details = await bchjs.Transaction.get(txid)
// console.log(`details: ${JSON.stringify(details, null, 2)}`)
assert.property(details.txData, 'txid')
})
})
if (process.env.TESTSLP) {
describe('#getOld', () => {
it('should get details about a non-SLP transaction', async () => {
const txid =
'2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
const result = await bchjs.Transaction.getOld(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// Assert that there are stanardized properties.
assert.property(result, 'txid')
assert.property(result, 'vin')
assert.property(result, 'vout')
assert.property(result.vout[0], 'value')
assert.property(result.vout[0].scriptPubKey, 'addresses')
// Assert that added properties exist.
assert.property(result.vin[0], 'address')
assert.property(result.vin[0], 'value')
assert.property(result, 'isValidSLPTx')
assert.equal(result.isValidSLPTx, false)
})
it('should get details about a SLP transaction', async () => {
const txid =
'266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1'
const result = await bchjs.Transaction.getOld(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// Assert that there are stanardized properties.
assert.property(result, 'txid')
assert.property(result, 'vin')
assert.property(result, 'vout')
assert.property(result.vout[0], 'value')
assert.property(result.vout[1].scriptPubKey, 'addresses')
// Assert that added properties exist.
assert.property(result.vout[0], 'tokenQty')
assert.equal(result.vout[0].tokenQty, null)
assert.property(result.vin[0], 'address')
assert.property(result.vin[0], 'value')
assert.property(result.vin[0], 'tokenQty')
assert.property(result, 'isValidSLPTx')
assert.equal(result.isValidSLPTx, true)
})
// it('should get problematic transaction', async () => {
// const txid = 'a55515de32577e296c512840bcaabed5823bb773fb4f8fd8e5197cc96cbc54d1'
//
// const result = await bchjs.Transaction.get(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// })
// TX a19f2f395a8b0e15b6202944c56834367d128f1e3630486a4756de53424a46fe has
// an input TXID (bd84bc1dd5ecd976165892306992401272f6bedeb37d7b2cdbf74fc4a55967a6)
// that is also a valid SLP tx, but is unrelated. Both TXs pass DAG validation,
// but for separate tokens.
it('should get problematic transaction', async () => {
const txid =
'a19f2f395a8b0e15b6202944c56834367d128f1e3630486a4756de53424a46fe'
const result = await bchjs.Transaction.getOld(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// The token ID should equal the txid for this Vin.
assert.equal(result.vin[2].txid, result.vin[2].tokenId)
})
})
}
})
-102
View File
@@ -1,102 +0,0 @@
/*
Integration tests for the bchjs. Only covers calls made to
rest.bitcoin.com.
*/
const chai = require('chai')
const assert = chai.assert
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
// Inspect utility used for debugging.
const util = require('util')
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe('#util', () => {
beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000)
})
describe('#validateAddress', () => {
it('should return false for testnet addr on mainnet', async () => {
const address = 'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false)
})
it('should return false for bad address', async () => {
const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peu'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false)
})
it('should validate valid address', async () => {
const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
'isvalid',
'address',
'scriptPubKey',
// "ismine",
// "iswatchonly",
'isscript'
])
assert.equal(result.isvalid, true)
})
it('should validate an array of addresses', async () => {
const address = [
'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z',
'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
]
const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
'isvalid',
'address',
'scriptPubKey',
// "ismine",
// "iswatchonly",
'isscript'
])
})
it('should throw error on array size rate limit', async () => {
try {
const dataMock = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
const data = []
for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.Util.validateAddress(data)
console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
assert.hasAnyKeys(err, ['error'])
assert.include(err.error, 'Array too large')
}
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+190
View File
@@ -0,0 +1,190 @@
/*
Integration tests for the utxo.js library.
*/
import chai from 'chai'
import BCHJS from '../../src/bch-js.js'
const { assert } = chai
const bchjs = new BCHJS()
// const bchjs = new BCHJS({ restURL: 'http://192.168.2.129:3000/v5/' })
describe('#UTXO', () => {
beforeEach(async () => {
// sandbox = sinon.createSandbox()
if (process.env.IS_USING_FREE_TIER) await sleep(3000)
})
describe('#hydrateTokenData', () => {
it('should hydrate token UTXOs', async () => {
const utxos = [
{
txid: '384e1b8197e8de7d38f98317af2cf5f6bcb50007c46943b3498a6fab6e8aeb7c',
vout: 1,
type: 'token',
qty: '10000000',
tokenId: 'a436c8e1b6bee3d701c6044d190f76f774be83c36de8d34a988af4489e86dd37',
address: 'bitcoincash:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvg8nfhq4m'
},
{
txid: '4fc789405d58ec612c69eba29aa56cf0c7f228349801114138424eb68df4479d',
vout: 1,
type: 'token',
qty: '100000000',
tokenId: 'df808a41672a0a0ae6475b44f272a107bc9961b90f29dc918d71301f24fe92fb',
address: 'bitcoincash:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvg8nfhq4m'
},
{
txid: '42054bba4d69bfe7801ece0cffc754194b04239034fdfe9dbe321ef76c9a2d93',
vout: 5,
type: 'token',
qty: '4764',
tokenId: 'f05faf13a29c7f5e54ab921750aafb6afaa953db863bd2cf432e918661d4132f',
address: 'bitcoincash:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvg8nfhq4m'
},
{
txid: '06938d0a0d15aa76524ffe61fe111d6d2b2ea9dd8dcd4c7c7744614ced370861',
vout: 5,
type: 'token',
qty: '238',
tokenId: 'f05faf13a29c7f5e54ab921750aafb6afaa953db863bd2cf432e918661d4132f',
address: 'bitcoincash:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvg8nfhq4m'
}
]
const result = await bchjs.Utxo.hydrateTokenData(utxos)
// console.log('result: ', result)
assert.property(result[0], 'ticker')
assert.property(result[0], 'name')
assert.property(result[0], 'qtyStr')
assert.property(result[0], 'documentUri')
assert.property(result[0], 'documentHash')
})
})
describe('#get', () => {
it('should hydrate address with BCH and SLP UTXOs', async () => {
const addr = 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// Assert expected properties exist.
assert.property(result, 'address')
assert.property(result, 'bchUtxos')
assert.property(result, 'slpUtxos')
assert.property(result.slpUtxos, 'type1')
assert.property(result.slpUtxos, 'nft')
assert.property(result, 'nullUtxos')
assert.isAbove(result.bchUtxos.length, 0)
assert.isAbove(result.infoUtxos.length, 0)
assert.isAbove(result.slpUtxos.type1.tokens.length, 0)
assert.equal(result.slpUtxos.type1.mintBatons.length, 0)
})
it('should handle Type1 minting batons', async () => {
const addr = 'simpleledger:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpv4awvv7m7'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// Assert that minting batons are correctly identified.
assert.isAbove(result.slpUtxos.type1.mintBatons.length, 0)
})
it('should return UTXOs for address with no SLP tokens', async () => {
const addr = 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(result.bchUtxos.length, 0)
assert.equal(result.slpUtxos.type1.tokens.length, 0)
})
it('should filter Group tokens and mint batons', async () => {
const addr = 'bitcoincash:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpvex9he79q'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(result.slpUtxos.group.tokens.length, 0)
assert.isAbove(result.slpUtxos.group.mintBatons.length, 0)
})
it('should filter NFTs', async () => {
const addr = 'bitcoincash:qrp4mlmsrtwlvjn4seuchvtmus06tuqmpvex9he79q'
const result = await bchjs.Utxo.get(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(result.slpUtxos.nft.tokens.length, 0)
})
})
describe('#isValid', () => {
it('should return true for valid UTXO with fullnode properties', async () => {
const utxo = {
txid: '260d4fb4006a330660c805327c840d569d7547b7e3e9659fb423b3a041c2e254',
vout: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, true)
})
it('should return true for valid UTXO with fulcrum properties', async () => {
const utxo = {
tx_hash: '260d4fb4006a330660c805327c840d569d7547b7e3e9659fb423b3a041c2e254',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, true)
})
it('should return true for valid UTXO with fullnode properties', async () => {
const utxo = {
txid: '17754221b29f189532d4fc2ae89fb467ad2dede30fdec4854eb2129b3ba90d7a',
vout: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result)
assert.equal(result, false)
})
it('should return true for valid UTXO with fulcrum properties', async () => {
const utxo = {
tx_hash: '17754221b29f189532d4fc2ae89fb467ad2dede30fdec4854eb2129b3ba90d7a',
tx_pos: 0
}
const result = await bchjs.Utxo.isValid(utxo)
// console.log('result: ', result
assert.equal(result, false)
})
it('should process output of Utxo.get()', async () => {
const utxo = await bchjs.Utxo.get('bitcoincash:qqgahqa5zkknmhmvsc98jndpwn3r77gqgc02x03jce')
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
const result = await bchjs.Utxo.isValid(utxo.bchUtxos[0])
assert.equal(result, true)
})
})
})
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+47 -4
View File
@@ -1,12 +1,15 @@
// Public npm libraries.
const assert = require('assert')
const Bitcoin = require('@psf/bitcoincashjs-lib')
import assert from 'assert'
// import { assert } from 'chai'
import Bitcoin from '@psf/bitcoincashjs-lib'
// Mocks
const fixtures = require('./fixtures/address.json')
import { createRequire } from 'module'
// Unit under test (uut)
const BCHJS = require('../../src/bch-js')
import BCHJS from '../../src/bch-js.js'
const require = createRequire(import.meta.url)
const fixtures = require('./fixtures/address.json')
let bchjs
function flatten (arrays) {
@@ -935,4 +938,44 @@ describe('#address.js', () => {
})
})
})
describe('#toEcashAddress', () => {
it('should convert a BCH address to an eCash address', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEcashAddress(cashAddr)
// console.log('result: ', result)
assert.equal(result, 'ecash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s8f6wu02p')
})
it('should convert a BCH address to an eCash address without a prefix', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEcashAddress(cashAddr, false)
// console.log('result: ', result)
assert.equal(result, 'qr24z7q6s26d9wr078lr2pxsmxg22cyn9s8f6wu02p')
})
})
describe('#toEtokenAddress', () => {
it('should convert a BCH address to an eToken address', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEtokenAddress(cashAddr)
// console.log('result: ', result)
assert.equal(result, 'etoken:qr24z7q6s26d9wr078lr2pxsmxg22cyn9sfhnv2gwk')
})
it('should convert a BCH address to an eToken address without a prefix', () => {
const cashAddr = 'bitcoincash:qr24z7q6s26d9wr078lr2pxsmxg22cyn9s7yw984vk'
const result = bchjs.Address.toEtokenAddress(cashAddr, false)
// console.log('result: ', result)
assert.equal(result, 'qr24z7q6s26d9wr078lr2pxsmxg22cyn9sfhnv2gwk')
})
})
})
+35 -25
View File
@@ -1,11 +1,13 @@
// Public npm libraries
const assert = require('assert')
import assert from 'assert'
// Mocks
const fixtures = require('./fixtures/bitcoincash.json')
import { createRequire } from 'module'
// Unit under test (uut)
const BCHJS = require('../../src/bch-js')
import BCHJS from '../../src/bch-js.js'
const require = createRequire(import.meta.url)
const fixtures = require('./fixtures/bitcoincash.json')
// const bchjs = new BCHJS()
let bchjs
@@ -264,10 +266,15 @@ describe('#BitcoinCash', () => {
})
})
describe('#bip38', () => {
describe('#bip38', function () {
// Increase timeout for BIP38 tests as they use CPU-intensive scrypt operations
// Each encrypt/decrypt operation takes ~5-6 seconds in Node.js v22
this.timeout(60000)
describe('#encryptBIP38', () => {
fixtures.bip38.encrypt.mainnet.forEach(fixture => {
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on mainnet`, () => {
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on mainnet`, function () {
this.timeout(60000)
const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
fixture.wif,
fixture.password
@@ -276,20 +283,22 @@ describe('#BitcoinCash', () => {
})
})
fixtures.bip38.encrypt.testnet.forEach(fixture => {
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on testnet`, () => {
const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
fixture.wif,
fixture.password
)
assert.equal(encryptedKey, fixture.encryptedKey)
})
})
// fixtures.bip38.encrypt.testnet.forEach(fixture => {
// it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on testnet`, function () {
// this.timeout(60000)
// const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
// fixture.wif,
// fixture.password
// )
// assert.equal(encryptedKey, fixture.encryptedKey)
// })
// })
})
describe('#decryptBIP38', () => {
fixtures.bip38.decrypt.mainnet.forEach(fixture => {
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on mainnet`, () => {
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on mainnet`, function () {
this.timeout(60000)
const wif = bchjs.BitcoinCash.decryptBIP38(
fixture.encryptedKey,
fixture.password,
@@ -299,16 +308,17 @@ describe('#BitcoinCash', () => {
})
})
fixtures.bip38.decrypt.testnet.forEach(fixture => {
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on testnet`, () => {
const wif = bchjs.BitcoinCash.decryptBIP38(
fixture.encryptedKey,
fixture.password,
'testnet'
)
assert.equal(wif, fixture.wif)
})
})
// fixtures.bip38.decrypt.testnet.forEach(fixture => {
// it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on testnet`, function () {
// this.timeout(60000)
// const wif = bchjs.BitcoinCash.decryptBIP38(
// fixture.encryptedKey,
// fixture.password,
// 'testnet'
// )
// assert.equal(wif, fixture.wif)
// })
// })
})
})
})
+51 -29
View File
@@ -1,11 +1,12 @@
const assert = require('assert')
const assert2 = require('chai').assert
const axios = require('axios')
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
const sinon = require('sinon')
import assert from 'assert'
import chai from 'chai'
import axios from 'axios'
import BCHJS from '../../src/bch-js.js'
import sinon from 'sinon'
const mockData = require('./fixtures/blockchain-mock')
import mockData from './fixtures/blockchain-mock.js'
const { assert: assert2 } = chai
const bchjs = new BCHJS()
describe('#Blockchain', () => {
describe('#getBestBlockHash', () => {
@@ -60,17 +61,41 @@ describe('#Blockchain', () => {
}
it('should get block by hash', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
sandbox.stub(axios, 'get').returns(resolved)
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'post').returns(resolved)
bchjs.Blockchain.getBlock(
const blockhash =
'00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09'
)
bchjs.Blockchain.getBlock(blockhash)
.then(result => {
assert.deepStrictEqual(data, result)
})
.then(done, done)
})
it('should throw error if blockhash is not provided', async () => {
try {
await bchjs.Blockchain.getBlock()
assert2.fail('Unexpected result')
} catch (err) {
assert2.include(err.message, 'blockhash must be a string')
}
})
it('should handle response error', async () => {
try {
const error = new Error()
error.response = {
data: 'Test Error'
}
sandbox.stub(axios, 'post').throws(error)
const blockhash =
'00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09'
await bchjs.Blockchain.getBlock(blockhash)
assert2.fail('Unexpected result')
} catch (err) {
assert2.include(err.message, 'Test Error')
}
})
})
describe('#getBlockchainInfo', () => {
@@ -105,7 +130,7 @@ describe('#Blockchain', () => {
}
it('should get blockchain info', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockchainInfo()
@@ -123,7 +148,7 @@ describe('#Blockchain', () => {
const data = 527810
it('should get block count', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockCount()
@@ -142,7 +167,7 @@ describe('#Blockchain', () => {
'000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0'
it('should get block hash by height', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockHash(527810)
@@ -177,7 +202,7 @@ describe('#Blockchain', () => {
}
it('should get block header by hash', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockHeader(
@@ -198,7 +223,7 @@ describe('#Blockchain', () => {
const data = '577528469277.1339'
it('should get difficulty', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getDifficulty()
@@ -216,7 +241,7 @@ describe('#Blockchain', () => {
const data = 'Transaction not in mempool'
it('should get mempool ancestors', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolAncestors(
@@ -239,7 +264,7 @@ describe('#Blockchain', () => {
}
it('should get mempool descendants', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolDescendants(
@@ -262,7 +287,7 @@ describe('#Blockchain', () => {
}
it('should get mempool entry', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolEntry(
@@ -290,7 +315,7 @@ describe('#Blockchain', () => {
}
it('should get mempool info', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolInfo()
@@ -331,7 +356,7 @@ describe('#Blockchain', () => {
}
it('should get mempool info', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getRawMempool()
@@ -355,10 +380,7 @@ describe('#Blockchain', () => {
try {
await bchjs.Blockchain.getTxOut('badtxid')
} catch (err) {
assert2.include(
err.message,
'txid needs to be a proper transaction ID'
)
assert2.include(err.message, 'txid needs to be a proper transaction ID')
}
})
@@ -430,7 +452,7 @@ describe('#Blockchain', () => {
}
it('should get TODO', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.preciousBlock()
@@ -448,7 +470,7 @@ describe('#Blockchain', () => {
const data = 'Cannot prune blocks because node is not in prune mode.'
it('should prune blockchain', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'post').returns(resolved)
bchjs.Blockchain.pruneBlockchain(507)
@@ -466,7 +488,7 @@ describe('#Blockchain', () => {
const data = true
it('should verify blockchain', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.verifyChain(3, 6)
@@ -484,7 +506,7 @@ describe('#Blockchain', () => {
const data = "proof must be hexadecimal string (not '')"
it('should verify utxo proof', done => {
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.verifyTxOutProof('3')
+6 -6
View File
@@ -1,8 +1,8 @@
const assert = require('assert')
const axios = require('axios')
const BCHJS = require('../../src/bch-js')
import assert from 'assert'
import axios from 'axios'
import BCHJS from '../../src/bch-js.js'
import sinon from 'sinon'
const bchjs = new BCHJS()
const sinon = require('sinon')
describe('#Control', () => {
let sandbox
@@ -24,7 +24,7 @@ describe('#Control', () => {
relayfee: 0.00001,
errors: ''
}
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Control.getNetworkInfo()
@@ -47,7 +47,7 @@ describe('#Control', () => {
chunks_free: 1
}
}
const resolved = new Promise(resolve => resolve({ data: data }))
const resolved = new Promise(resolve => resolve({ data }))
sandbox.stub(axios, 'get').returns(resolved)
bchjs.Control.getMemoryInfo()
+5 -3
View File
@@ -1,8 +1,10 @@
import { createRequire } from 'module'
import assert from 'assert'
import BCHJS from '../../src/bch-js.js'
import { Buffer } from 'safe-buffer'
const require = createRequire(import.meta.url)
const fixtures = require('./fixtures/crypto.json')
const assert = require('assert')
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
const Buffer = require('safe-buffer').Buffer
describe('#Crypto', () => {
describe('#sha256', () => {
+67
View File
@@ -0,0 +1,67 @@
// Public npm libraries
import chai from 'chai'
import sinon from 'sinon'
// Unit under test (uut)
import BCHJS from '../../src/bch-js.js'
import mockData from './fixtures/dsproof-mock.js'
const { assert } = chai
let bchjs
const txid = 'ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e'
describe('#DSProof', () => {
let sandbox
beforeEach(() => {
bchjs = new BCHJS()
sandbox = sinon.createSandbox()
})
afterEach(() => sandbox.restore())
describe('#getDSProof', () => {
it('should throw error if input is not provided', async () => {
try {
await bchjs.DSProof.getDSProof()
assert.equal(false, true, 'unexpected error')
} catch (err) {
assert.include(err.message, 'txid is required')
}
})
it('should throw error txid is invalid', async () => {
try {
await bchjs.DSProof.getDSProof('txid')
assert.equal(false, true, 'unexpected error')
} catch (err) {
assert.include(err.message, 'txid must be of length 64')
}
})
it('should handle error', async () => {
try {
sandbox.stub(bchjs.DSProof.axios, 'get').throws(new Error('test error'))
await bchjs.DSProof.getDSProof(txid)
assert.equal(false, true, 'unexpected error')
} catch (err) {
assert.include(err.message, 'test error')
}
})
it('should get double spend proof', async () => {
try {
sandbox
.stub(bchjs.DSProof.axios, 'get')
.resolves({ data: mockData.dsproof })
const result = await bchjs.DSProof.getDSProof(txid)
assert.property(result, 'dspid')
assert.property(result, 'txid')
assert.property(result, 'outpoint')
assert.property(result, 'path')
assert.property(result, 'descendants')
assert.property(result.outpoint, 'txid')
assert.property(result.outpoint, 'vout')
} catch (error) {
assert.equal(false, true, 'unexpected error')
}
})
})
})
+57
View File
@@ -0,0 +1,57 @@
/*
Unit tests for eCash library.
*/
// Global npm libraries
import chai from 'chai'
import Ecash from '../../src/ecash.js'
const { assert } = chai
const uut = new Ecash()
describe('#eCash', () => {
describe('#toSatoshi', () => {
it('should convert XEC to satoshis', () => {
const xec = 10704.35
const result = uut.toSatoshi(xec)
assert.equal(result, 1070435)
})
it('should throw an error if input is not a number', () => {
try {
uut.toSatoshi('test')
assert.fail('Unexpected code path')
} catch (err) {
assert.equal(
err.message,
'input must be a floating number representing XEC'
)
}
})
})
describe('#toXec', () => {
it('should convert satoshis to XEC', () => {
const sats = 1070435
const result = uut.toXec(sats)
assert.equal(result, 10704.35)
})
it('should throw an error if input is not a number', () => {
try {
uut.toXec('test')
assert.fail('Unexpected code path')
} catch (err) {
assert.equal(
err.message,
'input must be a floating number representing satoshis'
)
}
})
})
})
+6 -4
View File
@@ -1,12 +1,14 @@
// Public npm libraries.
const assert = require('assert')
const Buffer = require('safe-buffer').Buffer
import assert from 'assert'
import { Buffer } from 'safe-buffer'
// Mocks
const fixtures = require('./fixtures/ecpair.json')
import { createRequire } from 'module'
// Unit under test (uut)
const BCHJS = require('../../src/bch-js')
import BCHJS from '../../src/bch-js.js'
const require = createRequire(import.meta.url)
const fixtures = require('./fixtures/ecpair.json')
// const bchjs = new BCHJS()
let bchjs
+7 -7
View File
@@ -1,13 +1,13 @@
const chai = require('chai')
import chai from 'chai'
import axios from 'axios'
import sinon from 'sinon'
import BCHJS from '../../src/bch-js.js'
import mockData from './fixtures/electrumx-mock.js'
const assert = chai.assert
const axios = require('axios')
const sinon = require('sinon')
const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS()
const mockData = require('./fixtures/electrumx-mock')
describe('#ElectrumX', () => {
let sandbox
beforeEach(() => (sandbox = sinon.createSandbox()))
+6 -5
View File
@@ -1,12 +1,13 @@
const assert = require('chai').assert
const sinon = require('sinon')
import chai from 'chai'
import sinon from 'sinon'
const BCHJS = require('../../src/bch-js')
import BCHJS from '../../src/bch-js.js'
import mockData from './fixtures/encryption-mock.js'
const { assert } = chai
// const bchjs = new BCHJS()
let bchjs
const mockData = require('./fixtures/encryption-mock')
describe('#Encryption', () => {
let sandbox
-10
View File
@@ -406,11 +406,6 @@
"wif": "L1XHKhaBAfkr2FJQn3pTfCMxz652WYfmvKj8xDCHCEDV9tWGcbYj",
"password": "1EBPIyj55eR8bVUov9",
"encryptedKey": "6PYWWnBNfNpSqEJZKcfwbrYgTTdb9PNiGjQJ8r9V6cvsZNKLfcZD8YefQc"
},
{
"wif": "L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu",
"password": "9GKVkabAHBMyAf",
"encryptedKey": "6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G"
}
],
"testnet": [
@@ -432,11 +427,6 @@
"wif": "L1XHKhaBAfkr2FJQn3pTfCMxz652WYfmvKj8xDCHCEDV9tWGcbYj",
"password": "1EBPIyj55eR8bVUov9",
"encryptedKey": "6PYWWnBNfNpSqEJZKcfwbrYgTTdb9PNiGjQJ8r9V6cvsZNKLfcZD8YefQc"
},
{
"wif": "L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu",
"password": "9GKVkabAHBMyAf",
"encryptedKey": "6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G"
}
],
"testnet": [
+1 -1
View File
@@ -39,7 +39,7 @@ const utxo = [
}
]
module.exports = {
export default {
balance,
utxo
}
+1 -1
View File
@@ -2,7 +2,7 @@
Mock data used for unit testing.
*/
module.exports = {
export default {
details: {
hash: '000000001c6aeec19265e9cc3ded8ba5ef5e63fae7747f30bf9c02c7bc8883f0',
size: 216,
+1 -1
View File
@@ -2,7 +2,7 @@
Mock data used for unit testing.
*/
module.exports = {
export default {
bestBlockHash:
'0000000000000000008e1f65f875703872544aa888c7ca6587f055f8f5fbd4bf',
+19
View File
@@ -0,0 +1,19 @@
/*
Mock data used for unit testing.
*/
const dsproof = {
dspid: '6234fff2a9dbcaa50e2c50d74e1d725a2bed1757d7a05a2db7a82df659554397',
txid: 'ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e',
outpoint: {
txid: '17ebef34f7e9a0692317dd6fbb43ffccff45b7d688a2a754dbccfc5e6d93ce3e',
vout: 1
},
path: ['ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e'],
descendants: [
'ee0df780b58f6f24467605b2589c44c3a50fc849fb8f91b89669a4ae0d86bc7e'
]
}
export default {
dsproof
}
+1 -1
View File
@@ -290,7 +290,7 @@ const txHistoryWithUnconfirmed = {
]
}
module.exports = {
export default {
utxo,
utxos,
balance,
+1 -1
View File
@@ -13,7 +13,7 @@ const failureMock = {
publicKey: 'not found'
}
module.exports = {
export default {
successMock,
failureMock
}
+1 -1
View File
@@ -118,7 +118,7 @@ const paidFileData = {
}
}
module.exports = {
export default {
uploadData,
paymentInfo,
mockNewFileModel,
-170
View File
@@ -1,170 +0,0 @@
/*
Mocking data for unit tests for the Ninsight library.
*/
const utxo = {
utxos: [
{
txid: '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
vout: 0,
amount: 0.00001,
satoshis: 1000,
height: 602405,
confirmations: 36459
}
],
legacyAddress: '15NCRBJsHaJy8As5bX1oh2YauRejnZ1MKF',
cashAddress: 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9',
slpAddress: 'simpleledger:qqh793x9au6ehvh7r2zflzguanlme760wuwzunhjfm',
scriptPubKey: '76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac',
asm:
'OP_DUP OP_HASH160 2fe2c4c5ef359bb2fe1a849f891cecffbcfb4f77 OP_EQUALVERIFY OP_CHECKSIG'
}
const unconfirmed = {
utxos: [
{
txid: '3904ffe6f8fba4ceda5e887130f60fcb18bdc7dcee10392a57f89475c5c108f1',
vout: 0,
amount: 0.03608203,
satoshis: 3608203,
confirmations: 0,
ts: 1559670801
}
],
legacyAddress: '1AyWs8U4HUnTLmxxFiGoJbsXauRsvBrcKW',
cashAddress: 'bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5',
slpAddress: 'simpleledger:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rkuk8mdxlf2',
scriptPubKey: '76a9146d695af951760b837c8e58b045b098f9c17e23b788ac'
}
const utxoPost = [utxo, utxo]
const unconfirmedPost = [unconfirmed, unconfirmed]
const transactions = {
pagesTotal: 1,
txs: [
{
txid: 'ec7bc8349386e3e1939bbdc4f8092fdbdd6a380734e68486b558cd594c451d5b',
version: 2,
locktime: 0,
vin: [
{
txid:
'4f1fc57c33659628938db740449bf92fb75799e1d5750a4aeef80eb52d6df1e0',
vout: 0,
sequence: 4294967295,
n: 0,
scriptSig: {
hex:
'483045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f',
asm:
'3045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f'
},
addr: '17HPz8RQ4XM6mjre6aspvqyj1j648CZidM',
valueSat: 1111,
value: 0.00001111,
doubleSpentTxID: null
},
{
txid:
'126d62c299e7e14c66fe0b485d13082c23641f003690462046bc24ad2d1180c1',
vout: 0,
sequence: 4294967295,
n: 1,
scriptSig: {
hex:
'47304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f',
asm:
'304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f'
},
addr: '17HPz8RQ4XM6mjre6aspvqyj1j648CZidM',
valueSat: 1000,
value: 0.00001,
doubleSpentTxID: null
}
],
vout: [
{
value: '0.00001736',
n: 0,
scriptPubKey: {
hex: '76a914d96ac75ca8df9729d278da50ccd7355c5785444e88ac',
asm:
'OP_DUP OP_HASH160 d96ac75ca8df9729d278da50ccd7355c5785444e OP_EQUALVERIFY OP_CHECKSIG',
addresses: ['1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP'],
type: 'pubkeyhash'
},
spentTxId: null,
spentIndex: null,
spentHeight: null
}
],
blockheight: -1,
confirmations: 0,
time: 1559673337,
valueOut: 0.00001736,
size: 339,
valueIn: 0.00002111,
fees: 0.00000375
}
],
legacyAddress: '1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP',
cashAddress: 'bitcoincash:qrvk436u4r0ew2wj0rd9pnxhx4w90p2yfc29ta0d2n',
currentPage: 0
}
const transactionsPost = [transactions, transactions]
const details = {
txid: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
version: 1,
locktime: 0,
vin: [
{
coinbase: '04ffff001d02fd04',
sequence: 4294967295,
n: 0
}
],
vout: [
{
value: '50.00000000',
n: 0,
scriptPubKey: {
hex:
'4104f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446aac',
asm:
'04f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446a OP_CHECKSIG',
addresses: ['1BW18n7MfpU35q4MTBSk8pse3XzQF8XvzT'],
type: 'pubkeyhash',
cashAddrs: ['bitcoincash:qpej6mkrwca4tvy2snq4crhrf88v4ljspysx0ueetk']
},
spentTxId: null,
spentIndex: null,
spentHeight: null
}
],
blockhash:
'00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
blockheight: 1000,
confirmations: 585610,
time: 1232346882,
blocktime: 1232346882,
isCoinBase: true,
valueOut: 50,
size: 135
}
const detailsPost = [details, details]
module.exports = {
utxo,
utxoPost,
unconfirmed,
unconfirmedPost,
transactions,
transactionsPost,
details,
detailsPost
}

Some files were not shown because too many files have changed in this diff Show More