Compare commits

...

199 Commits

Author SHA1 Message Date
getlarge 17d3a02cb3
Release 4.3.0 2022-02-17 06:09:10 +01:00
getlarge f9a4675726
Merge pull request #312 from bigchaindb/fet-improve-requests
feat: improve requests
2022-02-17 06:03:53 +01:00
getlarge 7a12ee7eb9
ci: extends wait delay 2022-02-16 08:17:44 +01:00
getlarge eee8da4b78
fix: use abort-controller pkg for node <15 2022-02-16 08:17:30 +01:00
getlarge 2f3b2dbca1
ci: run BCDB node in background 2022-02-16 08:05:51 +01:00
getlarge 334a3f4d2d
Merge branch 'master' into fet-improve-requests 2022-02-16 07:59:56 +01:00
getlarge 1864f6fbb4
ci: update watched branch 2022-02-16 07:57:31 +01:00
getlarge 2ffbe99a2b
ci: create GH workflow 2022-02-16 07:56:28 +01:00
getlarge ae13da59b4
ci: create GH action workflow 2022-02-16 07:38:57 +01:00
getlarge 30c15b962b
feat: export extra types 2022-02-15 14:13:13 +01:00
getlarge 1ba488b28f
fix: improve transaction typedefs 2022-02-15 14:13:04 +01:00
getlarge fbc3d79d98
feat: update connection typedefs 2022-02-15 14:12:27 +01:00
getlarge 46599f5446
feat: add `limit` query for transaction search requests 2022-02-15 14:11:30 +01:00
getlarge 8c0c72622d
feat: ensure timeout and request are properly cleared 2022-02-15 14:10:49 +01:00
getlarge c5fe1346b9
chore: update dependencies 2022-02-15 14:06:19 +01:00
getlarge dc353ee5bc
chore: update lint rules 2022-02-15 08:07:38 +01:00
getlarge 38819a5934
fix: improve promises handling 2022-02-15 08:06:31 +01:00
getlarge 34289b0640
chore: update wepback config
declare Buffer as webpack plugin
2022-02-15 08:06:05 +01:00
getlarge 1f95bec2be
chore: update dev dependencies 2022-02-15 08:04:36 +01:00
getlarge 7c1e8be400
Release 4.2.2 2021-03-11 13:07:46 +01:00
getlarge 6aeece49cb
fix: improve typedefs
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-11 13:05:14 +01:00
getlarge 71a231a50a
fix: add delegateSignatureAsync method
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-11 13:04:17 +01:00
getlarge 76c877c649
Release 4.2.1 2021-03-10 16:34:41 +01:00
getlarge f020a35ea2
fix: improve imports
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 16:31:43 +01:00
getlarge 9b395c14a6
fix: add missing types in package
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 16:15:20 +01:00
getlarge d29b9c2566
Release 4.2.0 2021-03-10 15:48:37 +01:00
getlarge 6aa5f0100c
Merge pull request #308 from bigchaindb/add-type-defs
Add type defs
2021-03-10 15:38:17 +01:00
getlarge 1779f6eef4
fix: add type for TransactionOutput.condition
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 15:37:09 +01:00
getlarge 44dfc8f825
Merge branch 'add-type-defs' of github.com:bigchaindb/js-bigchaindb-driver into add-type-defs 2021-03-10 13:59:24 +01:00
getlarge d5fd300cfc
fix: makeoutput input type
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:08 +01:00
getlarge 71fe66c1f5
fix: Crypto conditions parsers
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:07 +01:00
getlarge af90b97460
fix: refine Crypoconditions parsers types
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:06 +01:00
getlarge b177ca0de4
fix: refine types definitions
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:05 +01:00
getlarge 858acf2693
fix: add type definitions
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:04 +01:00
getlarge d26f667feb
fix: module exports
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 13:59:02 +01:00
getlarge c98cc8e499
fix: makeoutput input type 2021-03-10 13:58:38 +01:00
getlarge 2a104eb86b
fix: Crypto conditions parsers 2021-03-10 13:36:00 +01:00
getlarge 90a2cb2608
fix: refine Crypoconditions parsers types 2021-03-10 13:20:32 +01:00
getlarge 84bd4efe03
fix: refine types definitions 2021-03-10 11:03:53 +01:00
getlarge 5f6bef65c5
fix: add type definitions 2021-03-10 09:22:40 +01:00
getlarge cd5c529324
fix: module exports 2021-03-10 09:22:37 +01:00
getlarge 7fe904061a
Merge pull request #307 from bigchaindb/update-dependencies
Update dependencies
2021-03-10 09:21:13 +01:00
getlarge 902885f7d1
Merge branches 'update-dependencies' and 'update-dependencies' of github.com:bigchaindb/js-bigchaindb-driver into update-dependencies 2021-03-10 09:10:26 +01:00
getlarge abaa40b269
fix: run lint
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:10 +01:00
getlarge 611624fd7a
fix: lint config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:09 +01:00
getlarge 3d49a6755e
fix: update example
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:07 +01:00
getlarge 978585d649
fix: update test constants
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:06 +01:00
getlarge 43c541d6d7
fix: minor transaction module improvements
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:05 +01:00
getlarge 272e6d6ae0
fix: update release-it config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:03 +01:00
getlarge 736b2adc37
fix: update tests to latest AVA API
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:02 +01:00
getlarge dc7634c9db
fix: update delegateSignTransaction callback
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:49:01 +01:00
getlarge 42112acd3e
fix: update travis config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:59 +01:00
getlarge 656de69c64
fix: improve request errors
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:58 +01:00
getlarge 597ac56f1f
fix: update polyfills path
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:57 +01:00
getlarge 1b9bafa097
fix: regenerate doc
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:56 +01:00
getlarge e3cca78886
fix: update webpack config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:54 +01:00
getlarge 23c3fa50ef
fix: update babel and lint config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:53 +01:00
getlarge 551180bceb
fix: update dependencies and test config
Signed-off-by: getlarge <ed@getlarge.eu>
2021-03-10 08:48:44 +01:00
getlarge 86d02c2f04
fix: run lint 2021-03-09 14:20:00 +01:00
getlarge 90466cf6ae
fix: lint config 2021-03-09 14:19:10 +01:00
getlarge cc3aa3fdd3
fix: update example 2021-03-09 13:49:15 +01:00
getlarge f5cd60e63d
fix: update test constants 2021-03-09 13:49:06 +01:00
getlarge 317bdd4d0f
fix: minor transaction module improvements 2021-03-09 12:32:29 +01:00
getlarge 41ce1178c7
fix: update release-it config 2021-03-09 12:20:24 +01:00
getlarge ba87737d97
fix: update tests to latest AVA API 2021-03-09 10:57:37 +01:00
getlarge d5894deec4
fix: update delegateSignTransaction callback 2021-03-09 09:50:33 +01:00
getlarge 3c76d3bb21
fix: update travis config 2021-03-09 08:16:09 +01:00
getlarge 1f27cd2300
fix: improve request errors 2021-03-09 07:52:03 +01:00
getlarge 57a3e89871
fix: update polyfills path 2021-03-09 07:51:36 +01:00
getlarge e76c6227f8
fix: regenerate doc 2021-03-09 07:17:06 +01:00
getlarge ad7763f76c
fix: update webpack config 2021-03-09 07:16:51 +01:00
getlarge b3909b0f04
fix: update babel and lint config 2021-03-09 07:15:59 +01:00
getlarge f0df142efb
fix: update dependencies and test config 2021-03-09 07:14:38 +01:00
getlarge 6dbafa8fad
Merge pull request #304 from bigchaindb/delegated-signature
Delegated signature
2020-12-21 07:35:18 +01:00
getlarge 344702200d fix: remove transaction from delegated signature callback
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:02 +01:00
getlarge a4d8ff531b add example usage
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:01 +01:00
getlarge 54ecf63a82 update contact link
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:01 +01:00
getlarge f5c2e92c69 update tendermint version in docker compose
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:01 +01:00
getlarge 4b0d5c40b6 test delegated signature
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:01 +01:00
getlarge b2e4ef55bf add delegateSignTransaction static method
Signed-off-by: getlarge <ed@getlarge.eu>
2020-12-17 18:06:00 +01:00
David Dashyan f08ea00142
Merge pull request #302 from bigchaindb/fix-npm-release
Release 4.1.2
2020-05-12 10:20:02 +00:00
David Dashyan 34233584e1
Release 4.1.2
Fixing messed up 4.1.1 release.

Signed-off-by: David Dashyan <mail@davie.li>
2020-03-11 23:06:25 +03:00
Manolo ea572804e3
Merge pull request #293 from bigchaindb/add-release-process
Document the release process and update the "release-it" options
2019-09-26 10:49:05 +02:00
Jürgen Eckel d4dae793e9
Merge pull request #287 from bigchaindb/update-dependencies
Update some package dependencies
2019-09-25 22:35:59 +02:00
Troy McConaghy 667e2c9c71 Update release-it to 12.2.0
Signed-off-by: Troy McConaghy <troy@bigchaindb.com>
2019-05-23 09:20:05 +02:00
Troy McConaghy 5a966f6ab2 Update "release" command. Document release process
Signed-off-by: Troy McConaghy <troy@bigchaindb.com>
2019-05-23 09:18:59 +02:00
manolodewiner a3d1824a03 Release 4.1.1 2019-04-30 09:58:40 +02:00
Jürgen Eckel ba81d1b9be
Merge pull request #286 from bigchaindb/update-dependencies
Update tendermint version && dependencies to latest version
2019-04-29 10:05:30 +02:00
manolodewiner 69e9814ba5 update tendermint version && dependencies to latest version
Signed-off-by: manolodewiner <manolosingular@gmail.com>
2019-04-27 18:14:57 +02:00
Troy McConaghy b37bdcded5
Merge pull request #273 from bigchaindb/update-emails
Update emails
2018-12-11 20:34:05 +01:00
Troy McConaghy 1fe3d3e08d dev --> devs@bigchaindb.com 2018-12-11 20:28:10 +01:00
Troy McConaghy 4fbcdc19c5 Point Code of Contuct page to main BDB repo 2018-12-11 20:26:57 +01:00
Troy McConaghy f9570378d2 Change Travis CI URLs to use .com 2018-12-11 20:25:16 +01:00
Jernej Pregelj c33724e3bf string fixes 2018-11-06 11:46:24 +01:00
Jernej Pregelj 561a2960b7
Merge pull request #265 from DavidEdwards/fix-buffer-crash
Wrap Uint8Array in a Buffer
2018-11-06 11:45:58 +01:00
David Edwards b7a9c960a2 Should not use deprecated constructor. Use Buffer.from. 2018-11-06 11:00:35 +01:00
David Edwards e4d0efd967 Fixes #264. This wraps the given Uint8Array in a Buffer so that it doesn't cause a crash in base-x. 2018-11-06 10:10:53 +01:00
Troy McConaghy 994c8ef163
Merge pull request #251 from ttmc/update-docs-re-testnet
Update docs, anticipating upcoming testnet changes
2018-09-26 13:20:24 +02:00
Troy McConaghy 4fbac054b1 Remove testnet-specific subdomain & headers 2018-09-13 15:17:39 +02:00
Troy McConaghy 15e50ba96e Remove old testnet information 2018-09-13 14:41:30 +02:00
Manolo 21eb6a0850
Merge pull request #243 from bigchaindb/greenkeeper/babel-loader-8.0.1
Update babel-loader to the latest version 🚀
2018-09-05 12:25:42 +02:00
greenkeeper[bot] b30bdfddbd chore(package): update babel-loader to version 8.0.1 2018-09-01 21:57:04 +00:00
Manolo 78ebbe3d6d
Merge pull request #242 from bigchaindb/greenkeeper/babel-loader-8.0.0
Update babel-loader to the latest version 🚀
2018-08-31 15:36:00 +02:00
Jernej Pregelj 885c2478ad
Merge pull request #241 from bigchaindb/remove-votes-api
remove votes endpoint
2018-08-31 15:05:44 +02:00
Manolo 6db30fda33
Merge branch 'master' into greenkeeper/babel-loader-8.0.0 2018-08-31 14:58:00 +02:00
Manolo 355dd62a60
Merge branch 'master' into remove-votes-api 2018-08-31 14:56:14 +02:00
Manolo ffe25a6d80
Merge pull request #240 from bigchaindb/greenkeeper/babel-eslint-9.0.0
Update babel-eslint to the latest version 🚀
2018-08-31 14:53:39 +02:00
Manolo 3c82ae47da
Merge pull request #239 from manolodewiner/bep-14_roundrobin
Implementation of BEP-14
2018-08-31 14:53:03 +02:00
manolodewiner a99ccd57f1 remove boolean comparison for numbers & add docs 2018-08-31 14:33:21 +02:00
manolodewiner f5debab03a small refactor and add tests 2018-08-30 12:26:14 +02:00
manolodewiner 11892a1f6b handle timeout for each request 2018-08-29 16:39:15 +02:00
greenkeeper[bot] 885766520e chore(package): update babel-loader to version 8.0.0 2018-08-28 19:28:06 +00:00
Jernej Pregelj 2afbd3b398 remove votes endpoint 2018-08-28 15:38:36 +02:00
manolodewiner b30578d9ab remove unused headers 2018-08-28 14:27:53 +02:00
manolodewiner bd8db702c4 cap backoff time 2018-08-28 14:09:26 +02:00
greenkeeper[bot] 30f7ecd389 chore(package): update babel-eslint to version 9.0.0 2018-08-28 03:25:24 +00:00
manolodewiner e0cde66749 merge 2018-08-23 17:16:16 +02:00
manolodewiner ad8a889ecc add and fix tests 2018-08-23 17:14:59 +02:00
Manolo f4d1f93a5b
Merge branch 'master' into bep-14_roundrobin 2018-08-23 09:43:19 +02:00
manolodewiner 7d978286f5 created model for new connections 2018-08-22 10:10:09 +02:00
Troy McConaghy 80bf01eb55
Merge pull request #235 from ttmc/add-more-licensing-info
Add more licensing info
2018-08-13 13:51:44 +02:00
Troy McConaghy cc203c514b Reformat LICENSE-docs for readability 2018-08-10 14:50:09 +02:00
Troy McConaghy 54dfcf637f Add SPDX license info strings to all source files 2018-08-10 12:49:26 +02:00
Troy McConaghy 27509dcb89 Add LICENSE-docs file, and reference it in README.md 2018-08-10 12:28:17 +02:00
Troy McConaghy 4555e251e5 Remove "coding: utf-8" line in conf.py: not needed in Python 3 files 2018-08-10 12:22:08 +02:00
Manolo 124586dcbc
Merge pull request #234 from bigchaindb/greenkeeper/js-sha3-0.8.0
Update js-sha3 to the latest version 🚀
2018-08-06 10:30:09 +02:00
greenkeeper[bot] 5a88c03513 fix(package): update js-sha3 to version 0.8.0 2018-08-05 07:37:40 +00:00
Jernej Pregelj 9f0ef2525b
Merge pull request #232 from innoprenuer/master
updated driver version to 4.1.0
2018-07-20 14:10:34 +02:00
Manan Patel 3710992441 updated driver version to 4.1.0 2018-07-20 14:02:40 +02:00
Jernej Pregelj 62629df926
Merge pull request #225 from nemaniarjun/cov95
WIP: test-coverage-95
2018-07-20 11:06:44 +02:00
Arjun Nemani 5a9f3905c7 Add tests for sanitize.js
Installs rewire from npm and use it to test functions
in sanitize.js

Part of https://github.com/bigchaindb/js-bigchaindb-driver/issues/220
2018-07-19 21:24:12 +05:30
Arjun Nemani a3be6c63a6 Fix sanitize array filter
The code for filtering with array has a small mistake,
where it checks if the "key" of the object is included in
the filter array instead of the "value" at that key.

Part of https://github.com/bigchaindb/js-bigchaindb-driver/issue/220
2018-07-19 21:23:57 +05:30
Arjun Nemani 074b4f0871 Add test for baseRequest.js
This commit adds tests for baseRequest,
with the aim to improve the code coverage of the
whole repo.

Part of https://github.com/bigchaindb/js-bigchaindb-driver/issues/220
2018-07-19 21:20:08 +05:30
Arjun Nemani 48f7584374 Fix connection test
This commit fixes the "Payload thrown at incorrect API_PATH"
test, it uses the proper way to check async error throws,
taken from ava.js docs. Done with the aim to increase the
coverage and to ensure working tests. Added "transform-runtime"
to .babelrc to enable "await/async" syntax".

Part of https://github.com/bigchaindb/js-bigchaindb-driver/issues/220
2018-07-19 20:23:12 +05:30
Arjun Nemani 64713d3742 Add tests for format_text.js
This commit adds tests for format_text,
with the aim to improve the code coverage of the
whole repo.

Part of https://github.com/bigchaindb/js-bigchaindb-driver/issues/220
2018-07-19 20:23:12 +05:30
Jernej Pregelj aaad21895f
Merge pull request #227 from dmvt/reduce-driver-to-less-than-1-MB
reduces development driver size to ~683k by removing vendor sourceMaps
2018-07-18 15:41:32 +02:00
Dan Matthews 1b21c28d7d removes -w flag from the build:dist 2018-07-18 09:37:13 -04:00
Dan Matthews 28d9cfc0fa reduces development driver size to ~683k by removing vendor sourceMaps 2018-07-17 10:33:58 -04:00
Manolo b315b8fe68
Merge pull request #231 from bigchaindb/greenkeeper/babel-eslint-8.2.6
chore(package): update babel-eslint to version 8.2.6
2018-07-17 13:40:37 +02:00
Manolo 8628a91c49
Merge pull request #230 from bigchaindb/greenkeeper/documentation-8.0.1
chore(package): update documentation to version 8.0.1
2018-07-17 13:40:23 +02:00
manolodewiner 9f727b55d9 Merge branch 'master' into greenkeeper/babel-eslint-8.2.6 2018-07-17 12:03:12 +02:00
manolodewiner 180a7c2dc0 Merge branch 'master' into greenkeeper/documentation-8.0.1 2018-07-17 11:59:50 +02:00
Manolo 08c826de25
Merge pull request #229 from bigchaindb/greenkeeper/webpack-4.16.1
Greenkeeper/webpack 4.16.1
2018-07-17 11:43:40 +02:00
manolodewiner 4a38192f76 Merge branch 'master' into greenkeeper/webpack-4.16.1 2018-07-17 11:31:50 +02:00
Manolo 944f047060
Merge pull request #228 from bigchaindb/update-tendermint
Update tendermint and mongo version
2018-07-17 11:30:15 +02:00
manolodewiner ba4b488dca update tendermint and mongo version 2018-07-17 11:15:53 +02:00
greenkeeper[bot] 9f5ac7445b chore(package): update webpack to version 4.16.1 2018-07-16 09:13:18 +00:00
greenkeeper[bot] 2d8bdcf311 chore(package): update documentation to version 8.0.1 2018-07-16 03:58:50 +00:00
greenkeeper[bot] 71b2f0d934 chore(package): update babel-eslint to version 8.2.6 2018-07-12 14:27:44 +00:00
Jernej Pregelj ea4f9e4464
Merge pull request #219 from innoprenuer/master
removed redundant getTransaction func calls
2018-07-09 13:36:54 +02:00
Manan Patel 28bcc02f30 removed redundant getTransaction func calls 2018-07-06 16:51:10 +02:00
innoprenuer 96fd99e076
Merge pull request #218 from innoprenuer/master
updated examples with latest api functions
2018-07-06 14:58:58 +02:00
Manan Patel fadc1bd567 updated examples with latest api functions 2018-07-06 14:47:32 +02:00
Matthias Kretschmann 9dfd7e20bf
Release 4.1.0 2018-07-05 14:18:32 +02:00
Matthias Kretschmann 6376e538ab
Merge pull request #180 from tnguyen42/patch-4
Minor corrections and details
2018-07-05 14:16:47 +02:00
Matthias Kretschmann 64b3272dd0
Merge pull request #217 from bigchaindb/feature/api-doc
update API doc
2018-07-05 14:14:26 +02:00
Matthias Kretschmann 3fc4958f63
update API doc 2018-07-05 13:53:15 +02:00
Matthias Kretschmann 6a637f33e2
Merge pull request #216 from bigchaindb/feature/package-updates
bump dependencies
2018-07-05 13:47:53 +02:00
Matthias Kretschmann 4a212b29be
bump dependencies 2018-07-05 12:52:39 +02:00
Matthias Kretschmann 56166698f1
Merge pull request #215 from bigchaindb/greenkeeper/babel-plugin-add-module-exports-0.3.1
chore(package): update babel-plugin-add-module-exports to version 0.3.1
2018-07-05 12:45:03 +02:00
Matthias Kretschmann cbd2536cca
Merge pull request #214 from bigchaindb/greenkeeper/babel-eslint-8.2.5
chore(package): update babel-eslint to version 8.2.5
2018-07-05 12:44:50 +02:00
Matthias Kretschmann 1bbfe7b27b
Merge pull request #213 from bigchaindb/greenkeeper/webpack-4.15.0
chore(package): update webpack to version 4.15.0
2018-07-05 12:40:53 +02:00
greenkeeper[bot] 9189ba7b52 chore(package): update webpack to version 4.15.0 2018-07-04 20:27:40 +00:00
greenkeeper[bot] b4e273de75 chore(package): update babel-plugin-add-module-exports to version 0.3.1
Closes #212
2018-07-02 21:17:14 +00:00
Manolo 5c977696ba
Merge pull request #197 from bigchaindb/adding_asyncMethod
adding async method
2018-06-28 17:30:55 +02:00
Manolo 3dbee074a9
Merge pull request #207 from bigchaindb/greenkeeper/eslint-5.0.0
Update eslint to the latest version 🚀
2018-06-25 12:02:18 +02:00
Matthias Kretschmann df0b3d5888
modify eslint glob pattern 2018-06-25 11:42:17 +02:00
greenkeeper[bot] 156fc5ffcb chore(package): update babel-eslint to version 8.2.5 2018-06-23 16:33:15 +00:00
greenkeeper[bot] 409e79e4f3 chore(package): update eslint to version 5.0.0 2018-06-23 08:05:53 +00:00
manolodewiner 9077d6ce34 update docs 2018-06-19 16:58:42 +02:00
manolodewiner 34c82a1ae8 refactor code & add test 2018-06-19 16:52:23 +02:00
Matthias Kretschmann a3ff691310
Merge pull request #203 from bigchaindb/fix-copyright-year-in-docs
Problem: Copyright year wrong in docs
2018-06-15 11:45:20 +02:00
Troy McConaghy d0724b60f5
Problem: Copyright year wrong in docs
Solution: Compute the copyright year when generating the docs
2018-06-14 15:12:45 +02:00
Matthias Kretschmann d3630109d3
Release 4.0.2 2018-06-13 17:37:19 +02:00
Matthias Kretschmann edcc837cee
Merge pull request #202 from bigchaindb/greenkeeper/webpack-4.12.0
chore(package): update webpack to version 4.12.0
2018-06-13 16:47:03 +02:00
greenkeeper[bot] aedfe02230
chore(package): update webpack to version 4.12.0 2018-06-13 16:36:41 +02:00
Matthias Kretschmann 7932c9a1af
Merge pull request #201 from bigchaindb/greenkeeper/webpack-cli-3.0.4
chore(package): update webpack-cli to version 3.0.4
2018-06-13 16:34:20 +02:00
Matthias Kretschmann bc8c9f8f98
Merge pull request #200 from bigchaindb/greenkeeper/cross-env-5.2.0
chore(package): update cross-env to version 5.2.0
2018-06-13 16:26:06 +02:00
Matthias Kretschmann bf3794d243
Merge pull request #195 from bigchaindb/greenkeeper/sinon-6.0.0
Update sinon to the latest version 🚀
2018-06-13 16:21:45 +02:00
greenkeeper[bot] d080674c6f chore(package): update cross-env to version 5.2.0 2018-06-13 13:54:29 +00:00
amed83 d812e64b30 adding async method 2018-06-12 14:42:42 +02:00
greenkeeper[bot] 387a9be5af chore(package): update webpack-cli to version 3.0.4 2018-06-12 12:01:28 +00:00
greenkeeper[bot] b089d4b009 chore(package): update sinon to version 6.0.0 2018-06-11 06:44:49 +00:00
Manolo 206e4cec5f
Merge pull request #189 from bigchaindb/greenkeeper/nyc-12.0.1
Update nyc to the latest version 🚀
2018-06-06 09:09:52 +02:00
Manolo 437de5ffa3
Merge pull request #190 from bigchaindb/greenkeeper/webpack-cli-3.0.0
Update webpack-cli to the latest version 🚀
2018-06-06 09:09:14 +02:00
Manolo eb1559d2f9
Merge pull request #192 from bigchaindb/greenkeeper/documentation-8.0.0
Update documentation to the latest version 🚀
2018-06-06 09:08:50 +02:00
Manolo 2b665dc5ca
Merge pull request #193 from bigchaindb/fixing_forEach
changed forEach method
2018-06-06 09:06:00 +02:00
amed83 2021639139 changeing bad nameed variable 2018-06-05 16:47:17 +02:00
amed83 5993c4cd6b changed forEach method 2018-06-05 15:14:15 +02:00
greenkeeper[bot] 446583d019 chore(package): update documentation to version 8.0.0 2018-06-04 19:01:24 +00:00
greenkeeper[bot] 7d68195c74 chore(package): update webpack-cli to version 3.0.0 2018-06-02 14:40:05 +00:00
greenkeeper[bot] 9642928e75 chore(package): update nyc to version 12.0.1 2018-06-01 22:19:32 +00:00
Manolo b62471a709
Merge pull request #182 from bigchaindb/fix-integration-test
Problem: Test "Valid TRANSFER transaction with multiple Ed25519 inputs..." failing
2018-06-01 14:30:15 +02:00
manolodewiner 4639acbd34 resolve promise to avoid invalid input 2018-05-23 14:33:45 +02:00
Thanh-Quy Nguyen 80811b8c7a
Minor corrections and details
- Inconsistency corrected between conn and bdb at the beginning, while they are the same object
- Asset Creation and Transfer: Cleaned a little useless code that made the end of it not working (returning res.id instead of res... but the (res) arrow function block was an unnecessary step)
- Websocket example: added a precision for the testnet case requiring SSL and port 443
2018-05-22 21:07:38 +02:00
Matthias Kretschmann 9163284b4a
Merge pull request #178 from bigchaindb/greenkeeper/lint-staged-7.1.2
chore(package): update lint-staged to version 7.1.2
2018-05-22 11:19:39 +02:00
Manolo 5f32d685c1
Merge pull request #177 from bigchaindb/greenkeeper/documentation-7.0.0
Update documentation to the latest version 🚀
2018-05-22 09:06:18 +02:00
greenkeeper[bot] 36f88bc712 chore(package): update documentation to version 7.0.0 2018-05-22 05:05:48 +00:00
greenkeeper[bot] bb44ec4d2e chore(package): update lint-staged to version 7.1.2 2018-05-21 07:39:40 +00:00
75 changed files with 2856 additions and 770 deletions

View File

@ -1,11 +1,29 @@
{
"presets": [
"env"
],
"plugins": [
"transform-export-extensions",
"transform-object-assign",
"transform-object-rest-spread"
],
"sourceMaps": true
}
"presets": [
[
"@babel/preset-env",
{
"targets": [
"> 0.25%, not dead",
"not IE 11",
"maintained node versions"
]
}
]
],
"plugins": [
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-transform-object-assign",
"@babel/plugin-proposal-object-rest-spread",
[
"@babel/plugin-transform-runtime",
{
"absoluteRuntime": false,
"corejs": 3,
"helpers": true,
"regenerator": true
}
]
],
"sourceMaps": true
}

View File

@ -1,4 +1,8 @@
#!/bin/bash
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
sudo apt-get update
sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce

View File

@ -1,4 +1,8 @@
#!/bin/bash
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
set -e -x

View File

@ -1,4 +1,8 @@
#!/bin/bash
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
set -e -x

View File

@ -1,3 +1,6 @@
dist
node_modules
coverage
media
docs
compose

231
.eslintrc.js Normal file
View File

@ -0,0 +1,231 @@
module.exports = {
extends: ['eslint:recommended', 'airbnb-base', 'plugin:import/recommended'],
parser: '@babel/eslint-parser',
parserOptions: { requireConfigFile: false },
env: {
browser: true,
node: true,
},
settings: {
'import/ignore': ['node_modules', '.(scss|css)$', '.(jpe?g|png|gif|svg)'],
},
rules: {
/**
* Possible Errors
* http://eslint.org/docs/rus/#possible-errors
*/
// Allow dangling commas for multiline arrays and objects
// http://eslint.org/docs/rules/comma-dangle
'comma-dangle': [1, 'only-multiline'],
// Warn against use of console for non-error logging
// http://eslint.org/docs/rules/no-console
'no-console': [1, { allow: ['error'] }],
// Allow use of Object.prototypes builtins directly
// http://eslint.org/docs/rules/no-prototype-builtins
'no-prototype-builtins': [0],
/**
* Best Practices
* http://eslint.org/docs/rules/#best-practices
*/
// Allow else clauses after an if with a return
// http://eslint.org/docs/rules/no-else-return
'no-else-return': [0],
// Disallow reassignment of function parameters (but allow assigning to parameter's properties)
// http://eslint.org/docs/rules/no-param-reassign.html
'no-param-reassign': [2, { props: false }],
/**
* Variables
* http://eslint.org/docs/rules/#variables
*/
// Disallow use of variables and classes before they are defined
// http://eslint.org/docs/rules/no-use-before-define
'no-use-before-define': [2, { functions: false, classes: true }],
// Disallow declaration of variables that are not used in the code, unless they are prefixed by
// `ignored` (useful for creating subset objects through destructuring and rest objects)
// http://eslint.org/docs/rules/no-unused-vars
'no-unused-vars': [
2,
{
vars: 'local',
args: 'after-used',
varsIgnorePattern: 'ignored.+',
},
],
/**
* Stylelistic Issues
* (http://eslint.org/docs/rules/#stylistic-issues)
*/
// Enforce 4-space indents, except for switch cases
// http://eslint.org/docs/rules/indent
'indent': [2, 4, { SwitchCase: 1, VariableDeclarator: 1 }],
// Specify the maximum length of a code line to be 100
// http://eslint.org/docs/rules/max-len
'max-len': [
2,
{
code: 105, // Use 105 to give some leeway for *just* slightly longer lines when convienient
ignorePattern: '^(import|export) .* from .*$',
ignoreComments: false,
ignoreTrailingComments: true,
ignoreUrls: true,
},
],
// Require capitalization when using `new`, but don't require capitalized functions to be called
// with new
// http://eslint.org/docs/rules/new-cap
'new-cap': [2, { newIsCap: true, capIsNew: false }],
// Allow the continue statement
// http://eslint.org/docs/rules/no-continue
'no-continue': [0],
// Disallow un-paren'd mixes of different operators if they're not of the same precendence
// http://eslint.org/docs/rules/no-mixed-operators
'no-mixed-operators': [
2,
{
groups: [
['+', '-', '*', '/', '%', '**'],
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: true,
},
],
// Allow use of unary increment/decrement operators
// http://eslint.org/docs/rules/no-plusplus
'no-plusplus': [0],
// Always allow dangling underscores
// http://eslint.org/docs/rules/no-underscore-dangle
'no-underscore-dangle': [0],
// Require unix-style line breaks
// http://eslint.org/docs/rules/linebreak-style
'linebreak-style': [2, 'unix'],
// Require operators to always be at the end of a line, except for the ternary operator
// http://eslint.org/docs/rules/operator-linebreak
'operator-linebreak': [
2,
'after',
{ overrides: { '?': 'ignore', ':': 'ignore' } },
],
// Require properties to be consistently quoted. Force numbers to be quoted, as they can have
// weird behaviour during the coercion into a string)
// http://eslint.org/docs/rules/quote-props
'quote-props': [
2,
'consistent',
{ keywords: false, unnecessary: true, numbers: true },
],
// Require spaces before parens for anonymous function declarations
// http://eslint.org/docs/rules/space-before-function-paren
'space-before-function-paren': [2, { anonymous: 'always', named: 'never' }],
// Require a space immediately following the // or /* in a comment for most comments
// http://eslint.org/docs/rules/spaced-comment
'spaced-comment': [
2,
'always',
{
line: {
exceptions: ['-', '+'],
},
block: {
exceptions: ['*'],
},
},
],
// We don't like semicolons so kill them
// http://eslint.org/docs/rules/semi
'semi': [2, 'never'],
/**
* Import rules
* https://github.com/benmosher/eslint-plugin-import#rules
*/
// Ensure named imports coupled with named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
'import/named': 2,
// Ensure default import coupled with default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
'import/default': 2,
// Disallow namespace (wildcard) imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
'import/no-namespace': 2,
// Enforce imports to not specify a trailing .js extension
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
'import/extensions': [2, { js: 'never' }],
// Enforce module import order: builtin -> external -> internal
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
'import/order': [
2,
{
groups: [
'builtin',
'external',
['internal', 'parent', 'sibling', 'index'],
],
},
],
'import/no-extraneous-dependencies': ['error', { 'devDependencies': true }],
/**
* ES6-specific Issues
* (http://eslint.org/docs/rules/#ecmascript-6)
*/
'arrow-body-style': [0],
'arrow-parens': [0],
'arrow-spacing': [0],
'constructor-super': [0],
'generator-star-spacing': [0],
'no-class-assign': [0],
'no-confusing-arrow': [0],
'no-const-assign': [0],
'no-dupe-class-members': [0],
'no-duplicate-imports': [0],
'no-new-symbol': [0],
'no-restricted-imports': [0],
'no-this-before-super': [0],
'no-useless-computed-key': [0],
'no-useless-constructor': [0],
'no-useless-rename': [0],
'no-var': [0],
'object-shorthand': [0],
'prefer-arrow-callback': [0],
'prefer-const': [0],
'prefer-reflect': [0],
'prefer-rest-params': [0],
'prefer-spread': [0],
'prefer-template': [0],
'require-yield': [0],
'rest-spread-spacing': [0],
'sort-imports': [0],
'template-curly-spacing': [0],
'yield-star-spacing': [0],
},
}

View File

@ -1,3 +0,0 @@
{
"extends": "ascribe"
}

68
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,68 @@
name: CI
on:
push:
branches:
- master
paths-ignore:
- README.md
- API.md
- docs/*.rst
pull_request:
branches:
- master
types:
- ready_for_review
- opened
- reopened
- synchronize
paths-ignore:
- README.md
- API.md
- docs/*.rst
jobs:
test:
runs-on: ubuntu-latest
if: github.event_name == 'release' || github.event_name == 'push' || !github.event.pull_request.draft
timeout-minutes: 10
steps:
- name: Checkout the commit
uses: actions/checkout@v2
- name: Set up Node
uses: actions/setup-node@v2
with:
node-version: 14
- name: Cache dependencies
id: cache
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Run BigChainDB node
run: |
echo Building and starting up docker containers
docker-compose -f ./docker-compose.yml up -d
- name: Install dependencies
env:
HUSKY_SKIP_INSTALL: 'true'
run: npm install
- name: Lint
run: npm run lint
- name: Build
run: npm run build
# ensure BCDB node is up and running
- run: sleep 20
- name: Test
run: npm run test

1
.gitignore vendored
View File

@ -12,6 +12,7 @@
.vscode
.env
.genv
node_modules
dist

1
.husky/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_

View File

@ -12,6 +12,7 @@
.vscode
.env
.genv
node_modules
package-lock.json

View File

@ -1,3 +1,7 @@
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
sudo: required
services:
@ -6,9 +10,9 @@ services:
language: node_js
node_js:
- 8
- 9
- 10
- 12
- 14
cache:
directories:
@ -16,7 +20,7 @@ cache:
env:
global:
- DOCKER_COMPOSE_VERSION=1.19.0
- DOCKER_COMPOSE_VERSION=1.28.5
before_install:
- .ci/travis-before-install.sh

455
API.md
View File

@ -3,420 +3,539 @@
### Table of Contents
- [Ed25519Keypair][1]
- [Connection][2]
- [getBlock][3]
- [getTransaction][4]
- [listBlocks][5]
- [listOutputs][6]
- [listTransactions][7]
- [listVotes][8]
- [postTransaction][9]
- [postTransactionSync][10]
- [postTransactionCommit][11]
- [searchAssets][12]
- [searchMetadata][13]
- [Transaction][14]
- [serializeTransactionIntoCanonicalString][15]
- [makeCreateTransaction][16]
- [makeEd25519Condition][17]
- [makeOutput][18]
- [makeSha256Condition][19]
- [makeThresholdCondition][20]
- [makeTransferTransaction][21]
- [signTransaction][22]
- [ccJsonLoad][23]
- [ccJsonify][24]
- [Parameters][2]
- [Properties][3]
- [Connection][4]
- [Parameters][5]
- [getBlock][6]
- [Parameters][7]
- [getTransaction][8]
- [Parameters][9]
- [listBlocks][10]
- [Parameters][11]
- [listOutputs][12]
- [Parameters][13]
- [listTransactions][14]
- [Parameters][15]
- [postTransaction][16]
- [Parameters][17]
- [postTransactionSync][18]
- [Parameters][19]
- [postTransactionAsync][20]
- [Parameters][21]
- [postTransactionCommit][22]
- [Parameters][23]
- [searchAssets][24]
- [Parameters][25]
- [searchMetadata][26]
- [Parameters][27]
- [Transaction][28]
- [serializeTransactionIntoCanonicalString][29]
- [Parameters][30]
- [makeCreateTransaction][31]
- [Parameters][32]
- [makeEd25519Condition][33]
- [Parameters][34]
- [makeOutput][35]
- [Parameters][36]
- [makeSha256Condition][37]
- [Parameters][38]
- [makeThresholdCondition][39]
- [Parameters][40]
- [makeTransferTransaction][41]
- [Parameters][42]
- [signTransaction][43]
- [Parameters][44]
- [delegateSignTransaction][45]
- [Parameters][46]
- [delegateSignTransactionAsync][47]
- [Parameters][48]
- [ccJsonLoad][49]
- [Parameters][50]
- [ccJsonify][51]
- [Parameters][52]
## Ed25519Keypair
[src/Ed25519Keypair.js:12-17][25]
[src/Ed25519Keypair.js:16-21][53]
Type: [Object][26]
Type: [Object][54]
**Parameters**
### Parameters
- `seed` **[Buffer][27]?** A seed that will be used as a key derivation function
- `seed` **[Buffer][55]?** A seed that will be used as a key derivation function
**Properties**
### Properties
- `publicKey` **[string][28]**
- `privateKey` **[string][28]**
- `publicKey` **[string][56]**
- `privateKey` **[string][56]**
## Connection
[src/connection.js:8-168][29]
[src/connection.js:21-199][57]
Base connection
### Parameters
**Parameters**
- `path`
- `headers` (optional, default `{}`)
- `nodes`
- `headers` **[Object][54]** Common headers for every request (optional, default `{}`)
- `timeout` **float** Optional timeout in secs (optional, default `DEFAULT_TIMEOUT`)
### getBlock
[src/connection.js:44-50][30]
[src/connection.js:79-85][58]
**Parameters**
#### Parameters
- `blockHeight`
### getTransaction
[src/connection.js:55-61][31]
[src/connection.js:90-96][59]
**Parameters**
#### Parameters
- `transactionId`
### listBlocks
[src/connection.js:67-73][32]
[src/connection.js:102-108][60]
**Parameters**
#### Parameters
- `transactionId`
- `status`
### listOutputs
[src/connection.js:79-91][33]
[src/connection.js:114-126][61]
**Parameters**
#### Parameters
- `publicKey`
- `spent`
### listTransactions
[src/connection.js:97-104][34]
[src/connection.js:132-139][62]
**Parameters**
#### Parameters
- `assetId`
- `operation`
### listVotes
[src/connection.js:109-115][35]
**Parameters**
- `blockId`
### postTransaction
[src/connection.js:120-125][36]
[src/connection.js:144-146][63]
**Parameters**
#### Parameters
- `transaction`
### postTransactionSync
[src/connection.js:130-135][37]
[src/connection.js:151-156][64]
**Parameters**
#### Parameters
- `transaction`
### postTransactionAsync
[src/connection.js:161-166][65]
#### Parameters
- `transaction`
### postTransactionCommit
[src/connection.js:140-145][38]
[src/connection.js:171-176][66]
**Parameters**
#### Parameters
- `transaction`
### searchAssets
[src/connection.js:150-156][39]
[src/connection.js:181-187][67]
**Parameters**
#### Parameters
- `search`
### searchMetadata
[src/connection.js:161-167][40]
[src/connection.js:192-198][68]
**Parameters**
#### Parameters
- `search`
## Transaction
[src/transaction.js:12-253][41]
[src/transaction.js:16-288][69]
Construct Transactions
### serializeTransactionIntoCanonicalString
[src/transaction.js:18-25][42]
[src/transaction.js:22-29][70]
Canonically serializes a transaction into a string by sorting the keys
**Parameters**
#### Parameters
- `transaction`
- `null` **[Object][26]** (transaction)
- `null` **[Object][54]** (transaction)
Returns **[string][28]** a canonically serialized Transaction
Returns **[string][56]** a canonically serialized Transaction
### makeCreateTransaction
[src/transaction.js:76-83][43]
[src/transaction.js:80-87][71]
Generate a `CREATE` transaction holding the `asset`, `metadata`, and `outputs`, to be signed by
the `issuers`.
**Parameters**
#### Parameters
- `asset` **[Object][26]** Created asset's data
- `metadata` **[Object][26]** Metadata for the Transaction
- `outputs` **[Array][44]&lt;[Object][26]>** Array of Output objects to add to the Transaction.
- `asset` **[Object][54]** Created asset's data
- `metadata` **[Object][54]** Metadata for the Transaction
- `outputs` **[Array][72]&lt;[Object][54]>** Array of Output objects to add to the Transaction.
Think of these as the recipients of the asset after the transaction.
For `CREATE` Transactions, this should usually just be a list of
Outputs wrapping Ed25519 Conditions generated from the issuers' public
keys (so that the issuers are the recipients of the created asset).
- `issuers` **...[Array][44]&lt;[string][28]>** Public key of one or more issuers to the asset being created by this
- `issuers` **...[Array][72]&lt;[string][56]>** Public key of one or more issuers to the asset being created by this
Transaction.
Note: Each of the private keys corresponding to the given public
keys MUST be used later (and in the same order) when signing the
Transaction (`signTransaction()`).
Returns **[Object][26]** Unsigned transaction -- make sure to call signTransaction() on it before
Returns **[Object][54]** Unsigned transaction -- make sure to call signTransaction() on it before
sending it off!
### makeEd25519Condition
[src/transaction.js:92-103][45]
[src/transaction.js:96-101][73]
Create an Ed25519 Cryptocondition from an Ed25519 public key
to put into an Output of a Transaction
**Parameters**
#### Parameters
- `publicKey` **[string][28]** base58 encoded Ed25519 public key for the recipient of the Transaction
- `json` **[boolean][46]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
- `publicKey` **[string][56]** base58 encoded Ed25519 public key for the recipient of the Transaction
- `json` **[boolean][74]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][26]** Ed25519 Condition (that will need to wrapped in an Output)
Returns **[Object][54]** Ed25519 Condition (that will need to wrapped in an Output)
### makeOutput
[src/transaction.js:113-133][47]
[src/transaction.js:111-131][75]
Create an Output from a Condition.
Note: Assumes the given Condition was generated from a
single public key (e.g. a Ed25519 Condition)
**Parameters**
#### Parameters
- `condition` **[Object][26]** Condition (e.g. a Ed25519 Condition from `makeEd25519Condition()`)
- `amount` **[string][28]** Amount of the output (optional, default `'1'`)
- `condition` **[Object][54]** Condition (e.g. a Ed25519 Condition from `makeEd25519Condition()`)
- `amount` **[string][56]** Amount of the output (optional, default `'1'`)
Returns **[Object][26]** An Output usable in a Transaction
Returns **[Object][54]** An Output usable in a Transaction
### makeSha256Condition
[src/transaction.js:141-149][48]
[src/transaction.js:139-143][76]
Create a Preimage-Sha256 Cryptocondition from a secret to put into an Output of a Transaction
**Parameters**
#### Parameters
- `preimage` **[string][28]** Preimage to be hashed and wrapped in a crypto-condition
- `json` **[boolean][46]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
- `preimage` **[string][56]** Preimage to be hashed and wrapped in a crypto-condition
- `json` **[boolean][74]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][26]** Preimage-Sha256 Condition (that will need to wrapped in an Output)
Returns **[Object][54]** Preimage-Sha256 Condition (that will need to wrapped in an Output)
### makeThresholdCondition
[src/transaction.js:158-172][49]
[src/transaction.js:152-162][77]
Create an Sha256 Threshold Cryptocondition from threshold to put into an Output of a Transaction
**Parameters**
#### Parameters
- `threshold` **[number][50]**
- `subconditions` **[Array][44]** (optional, default `[]`)
- `json` **[boolean][46]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
- `threshold` **[number][78]**
- `subconditions` **[Array][72]** (optional, default `[]`)
- `json` **[boolean][74]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][26]** Sha256 Threshold Condition (that will need to wrapped in an Output)
Returns **[Object][54]** Sha256 Threshold Condition (that will need to wrapped in an Output)
### makeTransferTransaction
[src/transaction.js:195-216][51]
[src/transaction.js:185-206][79]
Generate a `TRANSFER` transaction holding the `asset`, `metadata`, and `outputs`, that fulfills
the `fulfilledOutputs` of `unspentTransaction`.
**Parameters**
#### Parameters
- `unspentOutputs`
- `outputs` **[Array][44]&lt;[Object][26]>** Array of Output objects to add to the Transaction.
- `outputs` **[Array][72]&lt;[Object][54]>** Array of Output objects to add to the Transaction.
Think of these as the recipients of the asset after the transaction.
For `TRANSFER` Transactions, this should usually just be a list of
Outputs wrapping Ed25519 Conditions generated from the public keys of
the recipients.
- `metadata` **[Object][26]** Metadata for the Transaction
- `unspentTransaction` **[Object][26]** Previous Transaction you have control over (i.e. can fulfill
- `metadata` **[Object][54]** Metadata for the Transaction
- `unspentTransaction` **[Object][54]** Previous Transaction you have control over (i.e. can fulfill
its Output Condition)
- `OutputIndices` **...[number][50]** Indices of the Outputs in `unspentTransaction` that this
- `OutputIndices` **...[number][78]** Indices of the Outputs in `unspentTransaction` that this
Transaction fulfills.
Note that listed public keys listed must be used (and in
the same order) to sign the Transaction
(`signTransaction()`).
Returns **[Object][26]** Unsigned transaction -- make sure to call signTransaction() on it before
Returns **[Object][54]** Unsigned transaction -- make sure to call signTransaction() on it before
sending it off!
### signTransaction
[src/transaction.js:229-252][52]
[src/transaction.js:219-243][80]
Sign the given `transaction` with the given `privateKey`s, returning a new copy of `transaction`
that's been signed.
Note: Only generates Ed25519 Fulfillments. Thresholds and other types of Fulfillments are left as
an exercise for the user.
**Parameters**
#### Parameters
- `transaction` **[Object][26]** Transaction to sign. `transaction` is not modified.
- `privateKeys` **...[string][28]** Private keys associated with the issuers of the `transaction`.
- `transaction` **[Object][54]** Transaction to sign. `transaction` is not modified.
- `privateKeys` **...[string][56]** Private keys associated with the issuers of the `transaction`.
Looped through to iteratively sign any Input Fulfillments found in
the `transaction`.
Returns **[Object][26]** The signed version of `transaction`.
Returns **[Object][54]** The signed version of `transaction`.
### delegateSignTransaction
[src/transaction.js:252-265][81]
Delegate signing of the given `transaction` returning a new copy of `transaction`
that's been signed.
#### Parameters
- `transaction` **[Object][54]** Transaction to sign. `transaction` is not modified.
- `signFn` **[Function][82]** Function signing the transaction, expected to return the fulfillment.
Returns **[Object][54]** The signed version of `transaction`.
### delegateSignTransactionAsync
[src/transaction.js:274-287][83]
Delegate signing of the given `transaction` returning a new copy of `transaction`
that's been signed.
#### Parameters
- `transaction` **[Object][54]** Transaction to sign. `transaction` is not modified.
- `signFn` **[Function][82]** Function signing the transaction, expected to resolve the fulfillment.
Returns **[Promise][84]&lt;[Object][54]>** The signed version of `transaction`.
## ccJsonLoad
[src/utils/ccJsonLoad.js:10-40][53]
[src/utils/ccJsonLoad.js:13-44][85]
Loads a crypto-condition class (Fulfillment or Condition) from a BigchainDB JSON object
**Parameters**
### Parameters
- `conditionJson` **[Object][26]**
- `conditionJson` **[Object][54]**
Returns **cc.Condition** Ed25519 Condition (that will need to wrapped in an Output)
## ccJsonify
[src/utils/ccJsonify.js:8-61][54]
[src/utils/ccJsonify.js:12-65][86]
Serializes a crypto-condition class (Condition or Fulfillment) into a BigchainDB-compatible JSON
**Parameters**
### Parameters
- `fulfillment` **cc.Fulfillment** base58 encoded Ed25519 public key for recipient of the Transaction
Returns **[Object][26]** Ed25519 Condition (that will need to wrapped in an Output)
Returns **[Object][54]** Ed25519 Condition (that will need to wrapped in an Output)
[1]: #ed25519keypair
[2]: #connection
[2]: #parameters
[3]: #getblock
[3]: #properties
[4]: #gettransaction
[4]: #connection
[5]: #listblocks
[5]: #parameters-1
[6]: #listoutputs
[6]: #getblock
[7]: #listtransactions
[7]: #parameters-2
[8]: #listvotes
[8]: #gettransaction
[9]: #posttransaction
[9]: #parameters-3
[10]: #posttransactionsync
[10]: #listblocks
[11]: #posttransactioncommit
[11]: #parameters-4
[12]: #searchassets
[12]: #listoutputs
[13]: #searchmetadata
[13]: #parameters-5
[14]: #transaction
[14]: #listtransactions
[15]: #serializetransactionintocanonicalstring
[15]: #parameters-6
[16]: #makecreatetransaction
[16]: #posttransaction
[17]: #makeed25519condition
[17]: #parameters-7
[18]: #makeoutput
[18]: #posttransactionsync
[19]: #makesha256condition
[19]: #parameters-8
[20]: #makethresholdcondition
[20]: #posttransactionasync
[21]: #maketransfertransaction
[21]: #parameters-9
[22]: #signtransaction
[22]: #posttransactioncommit
[23]: #ccjsonload
[23]: #parameters-10
[24]: #ccjsonify
[24]: #searchassets
[25]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/Ed25519Keypair.js#L12-L17 "Source code on GitHub"
[25]: #parameters-11
[26]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[26]: #searchmetadata
[27]: https://nodejs.org/api/buffer.html
[27]: #parameters-12
[28]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[28]: #transaction
[29]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L8-L168 "Source code on GitHub"
[29]: #serializetransactionintocanonicalstring
[30]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L44-L50 "Source code on GitHub"
[30]: #parameters-13
[31]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L55-L61 "Source code on GitHub"
[31]: #makecreatetransaction
[32]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L67-L73 "Source code on GitHub"
[32]: #parameters-14
[33]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L79-L91 "Source code on GitHub"
[33]: #makeed25519condition
[34]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L97-L104 "Source code on GitHub"
[34]: #parameters-15
[35]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L109-L115 "Source code on GitHub"
[35]: #makeoutput
[36]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L120-L125 "Source code on GitHub"
[36]: #parameters-16
[37]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L130-L135 "Source code on GitHub"
[37]: #makesha256condition
[38]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L140-L145 "Source code on GitHub"
[38]: #parameters-17
[39]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L150-L156 "Source code on GitHub"
[39]: #makethresholdcondition
[40]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/connection.js#L161-L167 "Source code on GitHub"
[40]: #parameters-18
[41]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L12-L253 "Source code on GitHub"
[41]: #maketransfertransaction
[42]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L18-L25 "Source code on GitHub"
[42]: #parameters-19
[43]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L76-L83 "Source code on GitHub"
[43]: #signtransaction
[44]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[44]: #parameters-20
[45]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L92-L103 "Source code on GitHub"
[45]: #delegatesigntransaction
[46]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[46]: #parameters-21
[47]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L113-L133 "Source code on GitHub"
[47]: #delegatesigntransactionasync
[48]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L141-L149 "Source code on GitHub"
[48]: #parameters-22
[49]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L158-L172 "Source code on GitHub"
[49]: #ccjsonload
[50]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[50]: #parameters-23
[51]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L195-L216 "Source code on GitHub"
[51]: #ccjsonify
[52]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/transaction.js#L229-L252 "Source code on GitHub"
[52]: #parameters-24
[53]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/utils/ccJsonLoad.js#L10-L40 "Source code on GitHub"
[53]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/Ed25519Keypair.js#L16-L21 "Source code on GitHub"
[54]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/691fadfd9887d59fcff4877d9f90521da11ef950/src/utils/ccJsonify.js#L8-L61 "Source code on GitHub"
[54]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[55]: https://nodejs.org/api/buffer.html
[56]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[57]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L21-L199 "Source code on GitHub"
[58]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L79-L85 "Source code on GitHub"
[59]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L90-L96 "Source code on GitHub"
[60]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L102-L108 "Source code on GitHub"
[61]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L114-L126 "Source code on GitHub"
[62]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L132-L139 "Source code on GitHub"
[63]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L144-L146 "Source code on GitHub"
[64]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L151-L156 "Source code on GitHub"
[65]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L161-L166 "Source code on GitHub"
[66]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L171-L176 "Source code on GitHub"
[67]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L181-L187 "Source code on GitHub"
[68]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/connection.js#L192-L198 "Source code on GitHub"
[69]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L16-L288 "Source code on GitHub"
[70]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L22-L29 "Source code on GitHub"
[71]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L80-L87 "Source code on GitHub"
[72]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[73]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L96-L101 "Source code on GitHub"
[74]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[75]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L111-L131 "Source code on GitHub"
[76]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L139-L143 "Source code on GitHub"
[77]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L152-L162 "Source code on GitHub"
[78]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[79]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L185-L206 "Source code on GitHub"
[80]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L219-L243 "Source code on GitHub"
[81]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L252-L265 "Source code on GitHub"
[82]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[83]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/transaction.js#L274-L287 "Source code on GitHub"
[84]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[85]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/utils/ccJsonLoad.js#L13-L44 "Source code on GitHub"
[86]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/76c877c649801f0a26351d03237e0b59c18bd3ef/src/utils/ccJsonify.js#L12-L65 "Source code on GitHub"

View File

@ -1,46 +1,7 @@
# Contributor Code of Conduct
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, sexual identity and orientation, or species—no picking on Wrigley for being a buffalo!
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at conduct@bigchaindb.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
See [https://github.com/bigchaindb/bigchaindb/blob/master/CODE_OF_CONDUCT.md](https://github.com/bigchaindb/bigchaindb/blob/master/CODE_OF_CONDUCT.md)

View File

@ -1,3 +1,8 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
.. highlight:: shell
============

4
LICENSE-docs Normal file
View File

@ -0,0 +1,4 @@
The official BigchainDB documentation, _except for the short code snippets
embedded within it_, is licensed under a Creative Commons Attribution-
ShareAlike 4.0 International license, the full text of which can be found
at http://creativecommons.org/licenses/by-sa/4.0/legalcode

View File

@ -1,3 +1,9 @@
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
# [![js-bigchaindb-driver](media/repo-banner@2x.png)](https://www.bigchaindb.com)
> Official JavaScript driver for [BigchainDB](https://github.com/bigchaindb/bigchaindb) to create transactions in Node.js and the browser.
@ -6,7 +12,7 @@
[![npm](https://img.shields.io/npm/v/bigchaindb-driver.svg)](https://www.npmjs.com/package/bigchaindb-driver)
[![codecov](https://codecov.io/gh/bigchaindb/js-bigchaindb-driver/branch/master/graph/badge.svg)](https://codecov.io/gh/bigchaindb/js-bigchaindb-driver)
[![js ascribe](https://img.shields.io/badge/js-ascribe-39BA91.svg)](https://github.com/ascribe/javascript)
[![Build Status](https://travis-ci.org/bigchaindb/js-bigchaindb-driver.svg?branch=master)](https://travis-ci.org/bigchaindb/js-bigchaindb-driver)
[![Build Status](https://travis-ci.com/bigchaindb/js-bigchaindb-driver.svg?branch=master)](https://travis-ci.com/bigchaindb/js-bigchaindb-driver)
[![Greenkeeper badge](https://badges.greenkeeper.io/bigchaindb/js-bigchaindb-driver.svg)](https://greenkeeper.io/)
- [Main Documentation](https://docs.bigchaindb.com/projects/js-driver/en/latest/usage.html)
@ -34,8 +40,9 @@
- [BigchainDB Documentation](#bigchaindb-documentation)
- [Speed Optimizations](#speed-optimizations)
- [Development](#development)
- [Release Process](#release-process)
- [Authors](#authors)
- [License](#license)
- [Licenses](#licenses)
---
@ -55,8 +62,11 @@ import driver from 'bigchaindb-driver'
```js
const driver = require('bigchaindb-driver')
const base58 = require('bs58');
const crypto = require('crypto');
const { Ed25519Sha256 } = require('crypto-conditions');
// BigchainDB server instance (e.g. https://test.bigchaindb.com/api/v1/)
// BigchainDB server instance (e.g. https://example.com/api/v1/)
const API_PATH = 'http://localhost:9984/api/v1/'
// Create a new keypair.
@ -82,6 +92,22 @@ const tx = driver.Transaction.makeCreateTransaction(
// Sign the transaction with private keys
const txSigned = driver.Transaction.signTransaction(tx, alice.privateKey)
// Or use delegateSignTransaction to provide your own signature function
function signTransaction() {
// get privateKey from somewhere
const privateKeyBuffer = Buffer.from(base58.decode(alice.privateKey))
return function sign(serializedTransaction, input, index) {
const transactionUniqueFulfillment = input.fulfills ? serializedTransaction
.concat(input.fulfills.transaction_id)
.concat(input.fulfills.output_index) : serializedTransaction
const transactionHash = crypto.createHash('sha3-256').update(transactionUniqueFulfillment).digest()
const ed25519Fulfillment = new Ed25519Sha256();
ed25519Fulfillment.sign(transactionHash, privateKeyBuffer);
return ed25519Fulfillment.serializeUri();
};
}
const txSigned = driver.Transaction.delegateSignTransaction(tx, signTransaction())
// Send the transaction off to BigchainDB
const conn = new driver.Connection(API_PATH)
@ -98,10 +124,10 @@ conn.postTransactionCommit(txSigned)
<meta charset="utf-8">
<title>BigchainDB boilerplate</title>
<!-- Adjust version to your needs -->
<script src="https://unpkg.com/bigchaindb-driver@4.0.0/dist/browser/bigchaindb-driver.window.min.js"></script>
<script src="https://unpkg.com/bigchaindb-driver@4.2.0/dist/browser/bigchaindb-driver.window.min.js"></script>
<script>
// BigchainDB server instance (e.g. https://test.bigchaindb.com/api/v1/)
// BigchainDB server instance (e.g. https://example.com/api/v1/)
const API_PATH = 'http://localhost:9984/api/v1/'
// Create a new keypair.
@ -179,25 +205,16 @@ After updating source files in `src/`, make sure to update the API documentation
npm run doc
```
## Release Process
See the file named [RELEASE_PROCESS.md](RELEASE_PROCESS.md).
## Authors
* inspired by [`js-bigchaindb-quickstart`](https://github.com/sohkai/js-bigchaindb-quickstart) of @sohkhai [thanks]
* BigchainDB <dev@bigchaindb.com>
* BigchainDB <contact@ipdb.global>
* BigchainDB contributors
## License
## Licenses
```
Copyright 2017 BigchainDB GmbH
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
See [LICENSE](LICENSE) and [LICENSE-docs](LICENSE-docs).

91
RELEASE_PROCESS.md Normal file
View File

@ -0,0 +1,91 @@
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
# Our Release Process
## Notes
BigchainDB follows
[the Python form of Semantic Versioning](https://packaging.python.org/tutorials/distributing-packages/#choosing-a-versioning-scheme)
(i.e. MAJOR.MINOR.PATCH),
which is almost identical
to [regular semantic versioning](http://semver.org/), but there's no hyphen, e.g.
- `0.9.0` for a typical final release
- `4.5.2a1` not `4.5.2-a1` for the first Alpha release
- `3.4.5rc2` not `3.4.5-rc2` for Release Candidate 2
**Note:** For Git tags (which are used to identify releases on GitHub), we append a `v` in front.
We follow [BEP-1](https://github.com/bigchaindb/BEPs/tree/master/1), which is our variant of C4, the Collective Code Construction Contract, so a release is just a [tagged commit](https://git-scm.com/book/en/v2/Git-Basics-Tagging) on the `master` branch, i.e. a label for a particular Git commit.
## Steps
1. Make sure you have a recent version of node and npm.
1. `npm install`
1. Update all npm package dependencies, where possible. You might have to freeze some versions. Run all tests locally (`npm run test`) and make sure they pass. Make a pull request (to be merged into the `master` branch) and make sure all tests are passing there (in Travis). Merge the pull request.
1. Make sure your local `master` branch is in sync with GitHub: `git checkout master` and `git pull`
1. Do a test build:
`npm run build`
If that fails, then get it working.
1. We use the [release-it](https://www.npmjs.com/package/release-it) package (from npm) to automate most of the release. Make sure you have a recent version.
1. Login to npm using your npm credentials, so you can publish a new [bigchaindb-driver](https://www.npmjs.com/package/bigchaindb-driver) package there. (The npm account must have permission to do so).
`npm login`
1. release-it needs a Github personal access token so it can interact with GitHub on your behalf. To get one, go to:
[https://github.com/settings/tokens](https://github.com/settings/tokens)
and then make that token available as an environment variable, e.g.
`export GITHUB_TOKEN="f941e0..."`
1. Do the release:
- For a patch release, do `npm run release`
- For a minor release, do `npm run release-minor`
- For a major release, do `npm run release-major`
If your npm account is using two-factor authentication,
you will have to append a one-time password (OTP) like `--npm.otp=123456`.
The above command will automatically do a bunch of things:
- bump the project version in `package.json`, then git commit and git push it.
- create a new Git tag of the form `v{verson}`, e.g. `v1.2.3`
- create a new [GitHub release](https://github.com/bigchaindb/js-bigchaindb-driver/releases).
- publish a new npm release
To see all the arguments passed to `release-it`, search for "release" in [package.json](package.json). The arguments are documented in the [release-it GitHub repo](https://github.com/release-it/release-it).
1. Make sure everything worked as expected.
- Was the version number bumped properly in [package.json](package.json)?
- Was a new Git tag created? See the [list of tags](https://github.com/bigchaindb/js-bigchaindb-driver/tags).
- Was a new GitHub release created? See the [list of releases](https://github.com/bigchaindb/js-bigchaindb-driver/releases).
- Was a new npm package published on npm? [Check on npmjs.com](https://www.npmjs.com/package/bigchaindb-driver).
1. You can edit the description of the GitHub release to add or remove details.
If the docs were updated since the last release, [login to readthedocs.org](https://readthedocs.org/accounts/login/) and go to the **BigchainDB JavaScript Driver** project, then:
1. Click on "Builds", select "latest" from the drop-down menu, then click the "Build Version:" button.
1. Wait for the build of "latest" to finish. This can take a few minutes.
1. Go to Admin --> Advanced Settings
and make sure that "Default branch:" (i.e. what "latest" points to)
is set to the new release's tag, e.g. `v0.9.1`.
(It won't be an option if you didn't wait for the build of "latest" to finish.)
Then scroll to the bottom and click "Save".
1. Go to Admin --> Versions
and under **Choose Active Versions**, do these things:
1. Make sure that the new version's tag is "Active" and "Public"
1. Make sure the **stable** branch is _not_ active.
1. Scroll to the bottom of the page and click "Save".
Congratulations, you have released a new version of the BigchainDB JavaScript Driver!

View File

@ -1,8 +1,12 @@
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
version: '2.1'
services:
mongodb:
image: mongo:3.4.13
image: mongo:3.6
ports:
- "27017"
command: mongod
@ -17,23 +21,23 @@ services:
BIGCHAINDB_SERVER_BIND: 0.0.0.0:9984
BIGCHAINDB_WSSERVER_HOST: 0.0.0.0
BIGCHAINDB_TENDERMINT_HOST: tendermint
BIGCHAINDB_TENDERMINT_PORT: 46657
BIGCHAINDB_TENDERMINT_PORT: 26657
ports:
- "9984:9984"
- "9985:9985"
- "46658"
- "26658"
healthcheck:
test: ["CMD", "bash", "-c", "curl http://bigchaindb:9984 && curl http://tendermint:46657/abci_query"]
test: ["CMD", "bash", "-c", "curl http://bigchaindb:9984 && curl http://tendermint:26657/abci_query"]
interval: 3s
timeout: 5s
retries: 3
command: -l DEBUG start
tendermint:
image: tendermint/tendermint:0.19.2
volumes:
- ./compose/tendermint/tmdata/config.toml:/tendermint/config.toml
image: tendermint/tendermint:v0.31.5
# volumes:
# - ./tmdata:/tendermint
entrypoint: ''
ports:
- "46656"
- "46657"
command: sh -c "tendermint init && tendermint node --consensus.create_empty_blocks=false --proxy_app=tcp://bigchaindb:46658"
- "26656"
- "26657"
command: sh -c "tendermint init && tendermint node --consensus.create_empty_blocks=false --proxy_app=tcp://bigchaindb:26658"

View File

@ -1,2 +1,8 @@
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
# BigchainDBJavaScriptDriverDocs
BigchainDB JavaScript Driver Documentation with Sphinx

View File

@ -1,3 +1,3 @@
Sphinx>=1.6.3
Sphinx~=1.0
recommonmark>=0.4.0
sphinx-rtd-theme>=0.2.4

View File

@ -1,3 +1,8 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
=================
Advanced Examples
=================

View File

@ -1,5 +1,8 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
#
# BigchainDB Javascript Driver documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 2 15:39:03 2017.
@ -29,9 +32,10 @@
#
# needs_sphinx = '1.0'
from recommonmark.parser import CommonMarkParser
import datetime
import sphinx_rtd_theme
from recommonmark.parser import CommonMarkParser
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@ -58,7 +62,8 @@ master_doc = 'index'
# General information about the project.
project = 'BigchainDB Javascript Driver'
copyright = '2017, BigchainDB'
now = datetime.datetime.now()
copyright = str(now.year) + ', BigchainDB Contributors'
author = 'BigchainDB Contributors'
# The version info for the project you're documenting, acts as replacement for

View File

@ -1,3 +1,8 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
BigchainDB Javascript Driver Documentation
==========================================

View File

@ -1,3 +1,8 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
=========================
Quickstart / Installation
=========================

View File

@ -1,3 +1,8 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
BigchainDB JavaScript Driver
============================
@ -10,8 +15,8 @@ BigchainDB JavaScript Driver
.. image:: https://img.shields.io/badge/js-ascribe-39BA91.svg
:target: https://github.com/ascribe/javascript
.. image:: https://travis-ci.org/bigchaindb/js-bigchaindb-driver.svg?branch=master
:target: https://travis-ci.org/bigchaindb/js-bigchaindb-driver
.. image:: https://travis-ci.com/bigchaindb/js-bigchaindb-driver.svg?branch=master
:target: https://travis-ci.com/bigchaindb/js-bigchaindb-driver
.. image:: https://badges.greenkeeper.io/bigchaindb/js-bigchaindb-driver.svg
:target: https://greenkeeper.io/
@ -51,14 +56,17 @@ Older versions
anymore the `pollStatusAndFetchTransaction()` method as there are three
different ways of posting a transaction:
- `async` using the `postTransaction`: the response will return immediately and not wait to see if the transaction is valid.
- `commit` using the `postTransaction` or the `postTransactionCommit`: the response will return after the transaction is committed to a block.
- `sync` using the `postTransactionSync`: the response will return after the transaction is validated.
- `commit` using the `postTransactionCommit`: the response will return after the transaction is committed to a block.
- `async` using the `postTransactionAsync`: the response will return immediately and not wait to see if the transaction is valid.
By default in the docs we will use the `postTransactionCommit` as is way of
being sure that the transaction is validated and commited to a block, so
there will not be any issue if you try to do any other action with the asset immediately.
Note: In order to not create breaking changes, both methods `postTransaction` and `postTransactionCommit` are kept although
they do exactly the same
**Version 3.2.x**

View File

@ -1,8 +1,14 @@
.. Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
====================
Basic Usage Examples
====================
For the examples on this page, we assume you've :doc:`installed the bigchaindb_driver JavaScript package <quickstart>`,
For the examples on this page, we assume you've
:doc:`installed the bigchaindb_driver JavaScript package <quickstart>`,
and you have determined the BigchainDB Root URL (issue: move this to general docs)
of the node or cluster you want to connect to.
@ -26,27 +32,55 @@ Next, we define a constant containing the API path.
const API_PATH = 'http://localhost:9984/api/v1/'
Create Connection With BigchainDB
---------------------------------
Create a Connection with BigchainDB
-----------------------------------
A simple connection with BigchainDB can be established like this.
A simple connection with a BigchainDB node can be established like this:
.. code-block:: js
const conn = new driver.Connection(API_PATH)
It is also possible to connect to a node of the BigchainDB test network.
To do so, you need to pass the **app_id and app_key**.
If the BigchainDB node requires special HTTP request headers
(such as ``app_id`` and ``app_key``),
they can be included like this:
.. code-block:: js
let bdb = new driver.Connection('https://test.bigchaindb.com/api/v1/', {
app_id: 'Get one from testnet.bigchaindb.com',
app_key: 'Get one from testnet.bigchaindb.com'
const conn = new driver.Connection(API_PATH, {
app_id: 'app_id_value',
app_key: 'app_key_value'
})
A more complex connection can be created if the BigchainDB network
has several nodes, each with a different API path and different required headers.
The connection strategy will be the one specified in BEP-14_.
.. _BEP-14: https://github.com/bigchaindb/BEPs/tree/master/14#connection-strategy
.. code-block:: js
const conn = new driver.Connection([
API_PATH_1, // the first node does not use custom headers, only common headers
{endpoint: API_PATH_2,
headers: {app_id: 'your_app_id',
app_key: 'your_app_key'}},
{endpoint: API_PATH_3,
headers: {app_id: 'your_app_id',
app_key: 'your_app_key',
extra_header: 'extra value'}},
{endpoint: API_PATH_4,
headers: {app_id: 'your_app_id',
app_key: 'your_app_key',
other_header: 'other value'}},
{endpoint: API_PATH_5,
headers: {custom_auth: 'custom token'}],
{'sender_id': 'ab-12769'} // common header sent to all nodes
)
Cryptographic Identities Generation
-----------------------------------
Alice and Bob are represented by public/private key pairs. The private key is
used to sign transactions, meanwhile the public key is used to verify that a
signed transaction was indeed signed by the one who claims to be the signee.
@ -252,7 +286,7 @@ This call returns all the assets that match the string 'Bicycle Inc.', sorted by
Querying for Metadata
-------------------
---------------------
Similar as querying for assets, in BigchainDB you can query for metadata using simple text search.
This search is applied to all the strings inside the metadata payload and returns all the metadata payloads that match a given text search string.
@ -301,7 +335,7 @@ Recap: Asset Creation & Transfer
const driver = require('bigchaindb-driver')
// BigchainDB server instance or testnetwork (e.g. https://test.bigchaindb.com/api/v1/)
// BigchainDB server instance or testnetwork (e.g. https://example.com/api/v1/)
const API_PATH = 'http://localhost:9984/api/v1/'
// Create a new keypair for Alice and Bob
@ -365,11 +399,8 @@ Recap: Asset Creation & Transfer
// Post with commit so transaction is validated and included in a block
return conn.postTransactionCommit(txTransferBobSigned)
})
.then(res => {
console.log('Response from BDB server:', res)
return res.id
})
.then(tx => {
console.log('Response from BDB server:', tx)
console.log('Is Bob the owner?', tx['outputs'][0]['public_keys'][0] == bob.publicKey)
console.log('Was Alice the previous owner?', tx['inputs'][0]['owners_before'][0] == alice.publicKey )
})
@ -407,8 +438,13 @@ You can use the ``Ed25519Keypair()`` constructor as well without seed.
Websocket Event Stream API Usage
--------------------------------
The Event Stream API enables new ways to interact with BigchainDB, making it possible for your application to subscribe to all newlyconfirmed transactions that are happening in the system.
Below piece of code can be opened in your web browser. It will connect to your websocket (change it at ``var wsUri``). This web page will display all validated transactions.
The Event Stream API enables new ways to interact with BigchainDB,
making it possible for your application to subscribe
to all newlyconfirmed transactions that are happening in the system.
Below piece of code can be opened in your web browser.
It will connect to your websocket (if you are using the testnet, redefine
``var wsUri ='wss://insert-testnet-subdomain-here.com:443/api/v1/streams/valid_transactions'``).
This web page will display all validated transactions.
.. code-block:: html
@ -712,6 +748,7 @@ We will fulfill the first and second output of the create transaction (0, 1) bec
This gives us 3 tokens to redistribute. I want to give 1 token to Carly and 2 tokens Alice.
.. code-block:: js
const txTransferDivisibleInputs = driver.Transaction.makeTransferTransaction(
[{ tx: txTransferDivisibleSigned, output_index: 0 }, { tx: txTransferDivisibleSigned, output_index: 1 }],
[

View File

@ -1,3 +1,9 @@
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
# Updating js-bigchaindb-driver from v0.1.x to v0.3.0
The latest version of js-bigchaindb-driver contains breaking changes to its

View File

@ -1,4 +1,16 @@
{
"presets": ["es2015", "stage-3"],
"plugins": ["syntax-async-functions", "transform-runtime", "transform-regenerator", "transform-async-to-generator"]
}
"presets": [["@babel/preset-env"]],
"plugins": [
"@babel/plugin-syntax-async-generators",
[
"@babel/plugin-transform-runtime",
{
"absoluteRuntime": false,
"helpers": true,
"regenerator": true
}
],
"@babel/plugin-transform-regenerator",
"@babel/plugin-transform-async-to-generator"
]
}

View File

@ -1,3 +1,9 @@
<!---
Copyright BigchainDB GmbH and BigchainDB contributors
SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
Code is Apache-2.0 and docs are CC-BY-4.0
--->
# Quick Notes
`dotenv` is listed as a dependencies in `package.json`.
If you want to use this, add a `.env` file to the root of this project (same level as this `README.md` file)

View File

@ -14,23 +14,25 @@
"author": "BigchainDB",
"license": "MIT",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-plugin-syntax-async-functions": "^6.13.0",
"babel-plugin-transform-async-to-generator": "^6.8.0",
"babel-plugin-transform-regenerator": "^6.11.4",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-es2015": "^6.13.2",
"babel-preset-stage-3": "^6.11.0",
"nodemon": "^1.14.8",
"rimraf": "^2.6.2"
"@babel/cli": "^7.13.0",
"@babel/core": "^7.13.8",
"@babel/eslint-parser": "^7.13.8",
"@babel/node": "7.13.0",
"@babel/plugin-syntax-async-generators": "^7.8.4",
"@babel/plugin-transform-async-to-generator": "^7.13.0",
"@babel/plugin-transform-regenerator": "^7.12.13",
"@babel/plugin-transform-runtime": "^7.13.9",
"@babel/preset-env": "^7.13.9",
"@babel/register": "^7.13.8",
"babel-loader": "^8.2.2",
"nodemon": "^2.0.7",
"rimraf": "^3.0.2"
},
"repository": "/",
"private": true,
"dependencies": {
"bigchaindb-driver": "^3.2.0",
"bip39": "^2.5.0",
"dotenv": "^4.0.0"
"bigchaindb-driver": "^4.1.2",
"bip39": "^3.0.3",
"dotenv": "^8.2.0"
}
}

View File

@ -1,13 +1,16 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable import/no-unresolved */
const driver = require('bigchaindb-driver')
require('dotenv').config()
// ======== Preparation ======== //
const conn = new driver.Connection('https://test.bigchaindb.com/api/v1/', {
app_id: process.env.BIGCHAINDB_APP_ID,
app_key: process.env.BIGCHAINDB_APP_KEY
const conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
header1: 'header1_value',
header2: 'header2_value'
})
const alice = new driver.Ed25519Keypair()
@ -22,11 +25,9 @@ const assetdata = {
const metadata = { 'planet': 'earth' }
// Call async basic usage function
basicUsage()
async function basicUsage() {
// ======== Create Transaction Bicycle ======== //
const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
@ -41,22 +42,19 @@ async function basicUsage() {
const txCreateAliceSimpleSigned =
driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey)
// ======== POST CREATE Transaction ======== //
const createdTx = await conn.postTransactionCommit(txCreateAliceSimpleSigned)
// ======== Post Transaction and Fetch Result ======== //
await conn.postTransaction(txCreateAliceSimpleSigned)
await conn.pollStatusAndFetchTransaction(txCreateAliceSimpleSigned.id)
// ======== POST TRANSFER Transaction ======== //
const txTransferBob = driver.Transaction.makeTransferTransaction(
[{ tx: txCreateAliceSimpleSigned, output_index: 0 }],
[{ tx: createdTx, output_index: 0 }],
[driver.Transaction.makeOutput(driver.Transaction.makeEd25519Condition(bob.publicKey))],
{ price: '100 euro' }
)
const txTransferBobSigned = driver.Transaction.signTransaction(txTransferBob, alice.privateKey)
await conn.postTransaction(txTransferBobSigned)
await conn.pollStatusAndFetchTransaction(txTransferBobSigned.id)
await conn.postTransactionCommit(txTransferBobSigned)
// ======== Querying Assets ======== //
const assets = await conn.searchAssets('Bicycle Inc.')

View File

@ -1,13 +1,16 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable import/no-unresolved */
const driver = require('bigchaindb-driver')
require('dotenv').config()
// ======== Preparation ======== //
const conn = new driver.Connection('https://test.bigchaindb.com/api/v1/', {
app_id: process.env.BIGCHAINDB_APP_ID,
app_key: process.env.BIGCHAINDB_APP_KEY
const conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
header1: 'header1_value',
header2: 'header2_value'
})
const alice = new driver.Ed25519Keypair()
@ -22,7 +25,6 @@ const assetdata = {
const metadata = { 'planet': 'earth' }
// ======== Create Transaction Bicycle ======== //
const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
assetdata,
@ -36,17 +38,12 @@ const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
const txCreateAliceSimpleSigned =
driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey)
// ======== Post Transaction and Fetch Result ======== //
conn.postTransaction(txCreateAliceSimpleSigned)
// Check status of transaction every 0.5 seconds until fulfilled
.then(() => conn.pollStatusAndFetchTransaction(txCreateAliceSimpleSigned.id))
conn.postTransactionCommit(txCreateAliceSimpleSigned)
// ======== Transfer Bicycle to Bob ======== //
.then(() => {
.then((fetchedTx) => {
const txTransferBob = driver.Transaction.makeTransferTransaction(
[{ tx: txCreateAliceSimpleSigned, output_index: 0 }],
[{ tx: fetchedTx, output_index: 0 }],
[driver.Transaction.makeOutput(driver.Transaction.makeEd25519Condition(bob.publicKey))],
{ price: '100 euro' }
)
@ -54,15 +51,13 @@ conn.postTransaction(txCreateAliceSimpleSigned)
// Sign transfer transaction with Alice's private key
const txTransferBobSigned = driver.Transaction.signTransaction(txTransferBob, alice.privateKey)
return conn.postTransaction(txTransferBobSigned)
return conn.postTransactionCommit(txTransferBobSigned)
})
.then(res => conn.pollStatusAndFetchTransaction(res.id))
.then(tx => {
console.log('Is Bob the owner?', tx.outputs[0].public_keys[0] === bob.publicKey) // eslint-disable-line no-console
console.log('Was Alice the previous owner?', tx.inputs[0].owners_before[0] === alice.publicKey) // eslint-disable-line no-console
})
// ======== Search Asset by Serial Number ======== //
.then(() => conn.searchAssets('Bicycle Inc.'))
.then(assets => console.log('Found assets with serial number Bicycle Inc.:', assets)) // eslint-disable-line no-console

View File

@ -1,18 +1,20 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable import/no-unresolved */
const driver = require('bigchaindb-driver')
require('dotenv').config()
// ======== Preparation ======== //
const conn = new driver.Connection('https://test.bigchaindb.com/api/v1/', {
app_id: process.env.BIGCHAINDB_APP_ID,
app_key: process.env.BIGCHAINDB_APP_KEY
const conn = new driver.Connection('https://example.com/api/v1/', {
header1: 'header1_value',
header2: 'header2_value'
})
const alice = new driver.Ed25519Keypair()
// ======== Asset Array ======== //
const assetArray = []
assetArray.push({ 'bicycle': { 'serial_number': 'abc', 'manufacturer': 'BicyclesInc' } })
@ -21,7 +23,6 @@ assetArray.push({ 'bicycle': { 'serial_number': 'fgh', 'manufacturer': 'Bicycles
const metadata = { 'planet': 'Pluto' }
// ======== Create Transactions for bicycles ======== //
function createTx(assetdata) {
const txCreate = driver.Transaction.makeCreateTransaction(
@ -34,20 +35,16 @@ function createTx(assetdata) {
)
const txCreateSigned = driver.Transaction.signTransaction(txCreate, alice.privateKey)
return conn.postTransaction(txCreateSigned)
.then(() => conn.pollStatusAndFetchTransaction(txCreateSigned.id))
return conn.postTransactionCommit(txCreateSigned)
}
// ======== Execute all promises in order to post transactions and fetch them ======== //
Promise.all(assetArray.map(createTx))
// ======== Querying Assets for Assetdata ======== //
.then(() => conn.searchAssets('BicyclesInc'))
.then(assets => console.log('Found assets with serial number "BicyclesInc":', assets)) // eslint-disable-line no-console
// ======== Querying Assets for Metadata ======== //
.then(() => conn.searchMetadata('Pluto'))
.then(assets => console.log('Found assets with metadata "Pluto":', assets)) // eslint-disable-line no-console

View File

@ -1,3 +1,7 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable import/no-unresolved */
import bip39 from 'bip39'

View File

@ -1,6 +1,6 @@
{
"name": "bigchaindb-driver",
"version": "4.0.1",
"version": "4.3.0",
"description": "Node.js driver for BigchainDB",
"homepage": "https://www.bigchaindb.com/",
"bugs": "https://github.com/bigchaindb/js-bigchaindb-driver/issues",
@ -10,76 +10,83 @@
},
"license": "Apache-2.0",
"author": "BigchainDB",
"files": [
"dist",
"types"
],
"main": "./dist/node/index.js",
"browser": "./dist/browser/bigchaindb-driver.cjs2.min.js",
"types": "./types/index.d.ts",
"sideEffects": false,
"scripts": {
"lint": "eslint ./{src,test,examples}",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"build": "npm run clean && npm run build:cjs && npm run build:dist",
"build:bundle": "webpack",
"build:cjs": "cross-env BABEL_ENV=cjs babel ./src -d dist/node",
"build:dist": "cross-env NODE_ENV=production webpack -p",
"dev": "webpack -p -w",
"clean": "rimraf dist/bundle dist/node",
"test": "npm run lint && nyc ava test/ && npm run thanks && npm run report-coverage",
"build:dist": "cross-env NODE_ENV=production webpack",
"dev": "webpack -w",
"clean": "rimraf dist/bundle dist/browser dist/node",
"test": "npm run lint && nyc ava && npm run report-coverage",
"thanks": "cowsay Hi, thanks for your interest in BigchainDB. We appreciate your contribution!",
"release": "./node_modules/release-it/bin/release-it.js --src.tagName='v%s' --github.release --npm.publish --non-interactive",
"release-minor": "./node_modules/release-it/bin/release-it.js minor --src.tagName='v%s' --github.release --npm.publish --non-interactive",
"release-major": "./node_modules/release-it/bin/release-it.js major --src.tagName='v%s' --github.release --npm.publish --non-interactive",
"release": "read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it --src.tagName='v%s'",
"release-minor": "release-it minor --non-interactive",
"release-major": "release-it major --non-interactive",
"prepublishOnly": "npm run build",
"precommit": "lint-staged",
"report-coverage": "nyc report --reporter=lcov > coverage.lcov && codecov",
"doc": "node ./node_modules/documentation/bin/documentation.js build src/index.js -f md -o API.md -g --markdown-toc"
},
"lint-staged": {
"*.js": [
"eslint"
]
"doc": "documentation build src/index.js -f md -o API.md -g --markdown-toc"
},
"devDependencies": {
"ava": "^0.25.0",
"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.2",
"babel-loader": "^7.1.4",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-plugin-transform-export-extensions": "^6.22.0",
"babel-plugin-transform-object-assign": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015-no-commonjs": "0.0.2",
"babel-runtime": "^6.26.0",
"cross-env": "^5.1.4",
"documentation": "^6.3.2",
"eslint": "^4.19.1",
"eslint-config-ascribe": "^3.0.5",
"eslint-plugin-import": "^2.9.0",
"husky": "^0.14.3",
"lint-staged": "^7.0.0",
"nyc": "^11.6.0",
"release-it": "^7.2.1",
"rimraf": "^2.6.2",
"sinon": "^5.0.0",
"webpack": "^4.8.3",
"webpack-cli": "^2.0.13"
"@ava/babel": "^2.0.0",
"@babel/cli": "^7.17.0",
"@babel/core": "^7.17.2",
"@babel/eslint-parser": "^7.17.0",
"@babel/plugin-proposal-export-default-from": "^7.16.7",
"@babel/plugin-proposal-object-rest-spread": "^7.16.7",
"@babel/plugin-syntax-async-generators": "^7.8.4",
"@babel/plugin-transform-async-to-generator": "^7.16.8",
"@babel/plugin-transform-object-assign": "^7.16.7",
"@babel/plugin-transform-regenerator": "^7.16.7",
"@babel/plugin-transform-runtime": "^7.17.0",
"@babel/preset-env": "^7.16.11",
"@babel/register": "^7.17.0",
"ava": "^3.15.0",
"babel-loader": "^8.2.2",
"buffer": "^6.0.3",
"codecov": "^3.8.1",
"cross-env": "^7.0.3",
"documentation": "^13.2.5",
"eslint": "^8.9.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.25.4",
"husky": "^7.0.4",
"lint-staged": "^12.3.4",
"nyc": "^15.1.0",
"release-it": "^14.12.4",
"rewire": "^6.0.0",
"rimraf": "^3.0.2",
"sinon": "^13.0.1",
"terser-webpack-plugin": "^5.3.1",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2",
"webpack-merge": "^5.8.0",
"webpack-sources": "^3.2.3"
},
"dependencies": {
"browser-resolve": "^1.11.2",
"@babel/runtime-corejs3": "^7.17.2",
"abort-controller": "^3.0.0",
"bs58": "^4.0.1",
"buffer": "^5.1.0",
"clone": "^2.1.1",
"core-js": "^2.5.4",
"decamelize": "^2.0.0",
"es6-promise": "^4.2.4",
"fetch-ponyfill": "^6.0.1",
"crypto-conditions": "^2.0.1",
"isomorphic-fetch": "^2.2.1",
"js-sha3": "^0.7.0",
"js-utility-belt": "^1.5.0",
"clone": "^2.1.2",
"core-js": "^3.21.0",
"crypto-conditions": "2.2.1",
"decamelize": "^5.0.0",
"es6-promise": "^4.2.8",
"fetch-ponyfill": "^7.1.0",
"js-sha3": "^0.8.0",
"json-stable-stringify": "^1.0.1",
"query-string": "^6.0.0",
"sprintf-js": "^1.1.1",
"tweetnacl": "^1.0.0"
"query-string": "^7.1.1",
"sprintf-js": "^1.1.2",
"tweetnacl": "^1.0.3"
},
"keywords": [
"bigchaindb",
@ -88,9 +95,15 @@
"decentralized",
"dapp"
],
"lint-staged": {
"*.js": [
"eslint"
]
},
"ava": {
"files": [
"test/*.js"
"test/**/*.js",
"!test/constants.js"
],
"source": [
"**/*.{js,jsx}",
@ -102,8 +115,29 @@
"tap": true,
"powerAssert": false,
"require": [
"babel-register"
"@babel/register"
],
"babel": "inherit"
"babel": true
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"release-it": {
"github": {
"release": true
},
"git": {
"tagName": "v${version}"
},
"hooks": {
"before:init": [
"npm run test"
]
},
"npm": {
"publish": true
}
}
}

View File

@ -0,0 +1,38 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand, import/no-extraneous-dependencies */
const { ConcatSource } = require('webpack-sources')
module.exports = class AddVendorsPlugin {
constructor(base) {
this.base = base
}
apply(compiler) {
compiler.hooks.emit.tapAsync(
`AddVendorsPlugin ${this.base}`,
(compilation, callback) => {
const main = compilation.assets[`main.${this.base}`]
const mainMap = compilation.assets[`main.${this.base}.map`]
const vendor = compilation.assets[`vendors.${this.base}`]
if (main && vendor) {
const compiledAsset = new ConcatSource(main._value[0])
compiledAsset.add(vendor)
compiledAsset.add(main._value[1])
compilation.assets = {}
compilation.assets[this.base] = compiledAsset
} else if (main && mainMap) {
compilation.assets = {}
compilation.assets[this.base] = main
compilation.assets[`${this.base}.map`] = mainMap
}
callback()
}
)
}
}

View File

@ -1,5 +1,9 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import base58 from 'bs58'
import nacl from 'tweetnacl'
import { sign } from 'tweetnacl'
/**
* @public
@ -10,8 +14,8 @@ import nacl from 'tweetnacl'
* @property {string} privateKey
*/
export default function Ed25519Keypair(seed) {
const keyPair = seed ? nacl.sign.keyPair.fromSeed(seed) : nacl.sign.keyPair()
this.publicKey = base58.encode(keyPair.publicKey)
const keyPair = seed ? sign.keyPair.fromSeed(seed) : sign.keyPair()
this.publicKey = base58.encode(Buffer.from(keyPair.publicKey))
// tweetnacl's generated secret key is the secret key + public key (resulting in a 64-byte buffer)
this.privateKey = base58.encode(keyPair.secretKey.slice(0, 32))
this.privateKey = base58.encode(Buffer.from(keyPair.secretKey.slice(0, 32)))
}

View File

@ -1,3 +1,9 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
// TODO: remove abort-controller when using Node >=15
import AbortController from 'abort-controller'
import { Promise } from 'es6-promise'
import fetchPonyfill from 'fetch-ponyfill'
import { vsprintf } from 'sprintf-js'
@ -5,8 +11,65 @@ import { vsprintf } from 'sprintf-js'
import formatText from './format_text'
import stringifyAsQueryParam from './stringify_as_query_param'
const fetch = fetchPonyfill(Promise)
const fetch = fetchPonyfill({ Promise })
export function ResponseError(message, status, requestURI) {
this.name = 'ResponseError'
this.message = message
this.status = status
this.requestURI = requestURI
this.stack = new Error().stack
}
ResponseError.prototype = new Error()
/**
* @private
* Timeout function following https://github.com/github/fetch/issues/175#issuecomment-284787564
* @param {integer} obj Source object
* @param {Promise} filter Array of key names to select or function to invoke per iteration
* @param {AbortController} controller AbortController instance bound to fetch
* @return {Object} TimeoutError if the time was consumed, otherwise the Promise will be resolved
*/
function timeout(ms, promise, controller) {
return new Promise((resolve, reject) => {
const nodeTimeout = setTimeout(() => {
controller.abort()
const errorObject = {
message: 'TimeoutError',
}
reject(new Error(errorObject))
}, ms)
promise
.then((res) => {
clearTimeout(nodeTimeout)
resolve(res)
})
.catch((err) => {
clearTimeout(nodeTimeout)
reject(err)
})
})
}
/**
* @private
* @param {Promise} res Source object
* @return {Promise} Promise that will resolve with the response if its status was 2xx;
* otherwise rejects with the response
*/
function handleResponse(res) {
// If status is not a 2xx (based on Response.ok), assume it's an error
// See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
if (!(res && res.ok)) {
throw new ResponseError(
'HTTP Error: Requested page not reachable',
`${res.status} ${res.statusText}`,
res.url
)
}
return res
}
/**
* @private
@ -32,26 +95,35 @@ const fetch = fetchPonyfill(Promise)
* decamelized into snake case first.
* @param {*[]|Object} config.urlTemplateSpec Format spec to use to expand the url (see sprintf).
* @param {*} config.* All other options are passed through to fetch.
* @param {integer} requestTimeout Timeout for a single request
*
* @return {Promise} Promise that will resolve with the response if its status was 2xx;
* otherwise rejects with the response
* @return {Promise} If requestTimeout the timeout function will be called. Otherwise resolve the
* Promise with the handleResponse function
*/
export default function baseRequest(url, {
jsonBody, query, urlTemplateSpec, ...fetchConfig
} = {}) {
export default function baseRequest(
url,
{
jsonBody, query, urlTemplateSpec, ...fetchConfig
} = {},
requestTimeout = 0
) {
let expandedUrl = url
if (urlTemplateSpec != null) {
if (Array.isArray(urlTemplateSpec) && urlTemplateSpec.length) {
// Use vsprintf for the array call signature
expandedUrl = vsprintf(url, urlTemplateSpec)
} else if (urlTemplateSpec &&
} else if (
urlTemplateSpec &&
typeof urlTemplateSpec === 'object' &&
Object.keys(urlTemplateSpec).length) {
Object.keys(urlTemplateSpec).length
) {
expandedUrl = formatText(url, urlTemplateSpec)
} else if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('Supplied urlTemplateSpec was not an array or object. Ignoring...')
console.warn(
'Supplied urlTemplateSpec was not an array or object. Ignoring...'
)
}
}
@ -70,18 +142,16 @@ export default function baseRequest(url, {
fetchConfig.body = JSON.stringify(jsonBody)
}
return fetch.fetch(expandedUrl, fetchConfig)
.then((res) => {
// If status is not a 2xx (based on Response.ok), assume it's an error
// See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
if (!(res && res.ok)) {
const errorObject = {
message: 'HTTP Error: Requested page not reachable',
status: `${res.status} ${res.statusText}`,
requestURI: res.url
}
throw errorObject
}
return res
})
if (requestTimeout) {
const controller = new AbortController()
const { signal } = controller
return timeout(
requestTimeout,
fetch.fetch(expandedUrl, { ...fetchConfig, signal }),
controller
)
.then(handleResponse)
} else {
return fetch.fetch(expandedUrl, fetchConfig).then(handleResponse)
}
}

View File

@ -1,48 +1,83 @@
import request from './request'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import Transport from './transport'
const HEADER_BLACKLIST = ['content-type']
const DEFAULT_NODE = 'http://localhost:9984/api/v1/'
const DEFAULT_TIMEOUT = 20000 // The default value is 20 seconds
/**
* Base connection
*
* @param {String, Array} nodes Nodes for the connection. String possible to be backwards compatible
* with version before 4.1.0 version
* @param {Object} headers Common headers for every request
* @param {float} timeout Optional timeout in secs
*
*
*/
export default class Connection {
constructor(path, headers = {}) {
this.path = path
this.headers = Object.assign({}, headers)
export default class Connection {
// This driver implements the BEP-14 https://github.com/bigchaindb/BEPs/tree/master/14
constructor(nodes, headers = {}, timeout = DEFAULT_TIMEOUT) {
// Copy object
this.headers = { ...headers }
// Validate headers
Object.keys(headers).forEach(header => {
if (HEADER_BLACKLIST.includes(header.toLowerCase())) {
throw new Error(`Header ${header} is reserved and cannot be set.`)
}
})
this.normalizedNodes = []
if (!nodes) {
this.normalizedNodes.push(Connection.normalizeNode(DEFAULT_NODE, this.headers))
} else if (Array.isArray(nodes)) {
nodes.forEach(node => {
this.normalizedNodes.push(Connection.normalizeNode(node, this.headers))
})
} else {
this.normalizedNodes.push(Connection.normalizeNode(nodes, this.headers))
}
this.transport = new Transport(this.normalizedNodes, timeout)
}
getApiUrls(endpoint) {
return this.path + {
static normalizeNode(node, headers) {
if (typeof node === 'string') {
return { 'endpoint': node, 'headers': headers }
} else {
const allHeaders = { ...headers, ...node.headers }
return { 'endpoint': node.endpoint, 'headers': allHeaders }
}
}
static getApiUrls(endpoint) {
return {
'blocks': 'blocks',
'blocksDetail': 'blocks/%(blockHeight)s',
'outputs': 'outputs',
'transactions': 'transactions',
'transactionsSync': 'transactions?mode=sync',
'transactionsAsync': 'transactions?mode=async',
'transactionsCommit': 'transactions?mode=commit',
'transactionsDetail': 'transactions/%(transactionId)s',
'assets': 'assets',
'metadata': 'metadata',
'votes': 'votes'
'metadata': 'metadata'
}[endpoint]
}
_req(path, options = {}) {
// NOTE: `options.headers` could be undefined, but that's OK.
options.headers = Object.assign({}, options.headers, this.headers)
return request(path, options)
return this.transport.forwardRequest(path, options)
}
/**
* @param blockHeight
*/
getBlock(blockHeight) {
return this._req(this.getApiUrls('blocksDetail'), {
return this._req(Connection.getApiUrls('blocksDetail'), {
urlTemplateSpec: {
blockHeight
}
@ -53,7 +88,7 @@ export default class Connection {
* @param transactionId
*/
getTransaction(transactionId) {
return this._req(this.getApiUrls('transactionsDetail'), {
return this._req(Connection.getApiUrls('transactionsDetail'), {
urlTemplateSpec: {
transactionId
}
@ -65,7 +100,7 @@ export default class Connection {
* @param status
*/
listBlocks(transactionId) {
return this._req(this.getApiUrls('blocks'), {
return this._req(Connection.getApiUrls('blocks'), {
query: {
transaction_id: transactionId,
}
@ -85,7 +120,7 @@ export default class Connection {
if (spent !== undefined) {
query.spent = spent.toString()
}
return this._req(this.getApiUrls('outputs'), {
return this._req(Connection.getApiUrls('outputs'), {
query
})
}
@ -95,7 +130,7 @@ export default class Connection {
* @param operation
*/
listTransactions(assetId, operation) {
return this._req(this.getApiUrls('transactions'), {
return this._req(Connection.getApiUrls('transactions'), {
query: {
asset_id: assetId,
operation
@ -104,21 +139,17 @@ export default class Connection {
}
/**
* @param blockId
* @param transaction
*/
listVotes(blockId) {
return this._req(this.getApiUrls('votes'), {
query: {
block_id: blockId
}
})
postTransaction(transaction) {
return this.postTransactionCommit(transaction)
}
/**
* @param transaction
*/
postTransaction(transaction) {
return this._req(this.getApiUrls('transactions'), {
postTransactionSync(transaction) {
return this._req(Connection.getApiUrls('transactionsSync'), {
method: 'POST',
jsonBody: transaction
})
@ -127,8 +158,8 @@ export default class Connection {
/**
* @param transaction
*/
postTransactionSync(transaction) {
return this._req(this.getApiUrls('transactionsSync'), {
postTransactionAsync(transaction) {
return this._req(Connection.getApiUrls('transactionsAsync'), {
method: 'POST',
jsonBody: transaction
})
@ -138,7 +169,7 @@ export default class Connection {
* @param transaction
*/
postTransactionCommit(transaction) {
return this._req(this.getApiUrls('transactionsCommit'), {
return this._req(Connection.getApiUrls('transactionsCommit'), {
method: 'POST',
jsonBody: transaction
})
@ -147,10 +178,11 @@ export default class Connection {
/**
* @param search
*/
searchAssets(search) {
return this._req(this.getApiUrls('assets'), {
searchAssets(search, limit = 10) {
return this._req(Connection.getApiUrls('assets'), {
query: {
search
search,
limit
}
})
}
@ -158,10 +190,11 @@ export default class Connection {
/**
* @param search
*/
searchMetadata(search) {
return this._req(this.getApiUrls('metadata'), {
searchMetadata(search, limit = 10) {
return this._req(Connection.getApiUrls('metadata'), {
query: {
search
search,
limit
}
})
}

View File

@ -1,5 +1,8 @@
import { sprintf } from 'sprintf-js'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import { sprintf } from 'sprintf-js'
// Regexes taken from or inspired by sprintf-js
const Regex = {

View File

@ -1,6 +1,13 @@
export Ed25519Keypair from './Ed25519Keypair'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
export Connection from './connection'
export Transaction from './transaction'
export ccJsonLoad from './utils/ccJsonLoad'
export ccJsonify from './utils/ccJsonify'
import Ed25519Keypair from './Ed25519Keypair'
import Connection from './connection'
import Transaction from './transaction'
import ccJsonLoad from './utils/ccJsonLoad'
import ccJsonify from './utils/ccJsonify'
export {
ccJsonLoad, ccJsonify, Connection, Ed25519Keypair, Transaction
}

View File

@ -1,3 +1,7 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import baseRequest from './baseRequest'
import sanitize from './sanitize'
@ -7,32 +11,108 @@ const DEFAULT_REQUEST_CONFIG = {
}
}
const BACKOFF_DELAY = 500 // 0.5 seconds
const ERROR_FROM_SERVER = 'HTTP Error: Requested page not reachable'
/**
* @private
* Small wrapper around js-utility-belt's request that provides url resolving,
* default settings, and response handling.
*/
export default function request(url, config = {}) {
// Load default fetch configuration and remove any falsy query parameters
const requestConfig = Object.assign({}, DEFAULT_REQUEST_CONFIG, config, {
query: config.query && sanitize(config.query)
})
const apiUrl = url
if (requestConfig.jsonBody) {
requestConfig.headers = Object.assign({}, requestConfig.headers, {
'Content-Type': 'application/json'
})
export default class Request {
constructor(node) {
this.node = node
this.backoffTime = null
this.retries = 0
this.connectionError = null
}
if (!url) {
return Promise.reject(new Error('Request was not given a url.'))
async request(urlPath, config, timeout, maxBackoffTime) {
if (!urlPath) {
return Promise.reject(new Error('Request was not given a url.'))
}
// Load default fetch configuration and remove any falsy query parameters
const requestConfig = {
...this.node.headers,
...DEFAULT_REQUEST_CONFIG,
...config,
query: config.query && sanitize(config.query)
}
const apiUrl = this.node.endpoint + urlPath
if (requestConfig.jsonBody) {
requestConfig.headers = { ...requestConfig.headers, 'Content-Type': 'application/json' }
}
// If connectionError occurs, a timestamp equal to now +
// `backoffTimedelta` is assigned to the object.
// Next time the function is called, it either
// waits till the timestamp is passed or raises `TimeoutError`.
// If `ConnectionError` occurs two or more times in a row,
// the retry count is incremented and the new timestamp is calculated
// as now + the `backoffTimedelta`
// The `backoffTimedelta` is the minimum between the default delay
// multiplied by two to the power of the
// number of retries or timeout/2 or 10. See Transport class for that
// If a request is successful, the backoff timestamp is removed,
// the retry count is back to zero.
const backoffTimedelta = this.getBackoffTimedelta()
if (timeout != null && timeout < backoffTimedelta) {
const errorObject = {
message: 'TimeoutError'
}
throw errorObject
}
if (backoffTimedelta > 0) {
await Request.sleep(backoffTimedelta)
}
const requestTimeout = timeout ? timeout - backoffTimedelta : timeout
return baseRequest(apiUrl, requestConfig, requestTimeout)
.then((res) => {
this.connectionError = null
return res.json()
})
.catch(err => {
// ConnectionError
this.connectionError = err
})
.finally(() => {
this.updateBackoffTime(maxBackoffTime)
})
}
return baseRequest(apiUrl, requestConfig)
.then(res => res.json())
.catch(err => {
console.error(err)
throw err
updateBackoffTime(maxBackoffTime) {
if (!this.connectionError) {
this.retries = 0
this.backoffTime = null
} else if (this.connectionError.message === ERROR_FROM_SERVER) {
// If status is not a 2xx (based on Response.ok), throw error
this.retries = 0
this.backoffTime = null
throw this.connectionError
} else {
// Timeout or no connection could be stablished
const backoffTimedelta = Math.min(BACKOFF_DELAY * (2 ** this.retries), maxBackoffTime)
this.backoffTime = Date.now() + backoffTimedelta
this.retries += 1
if (this.connectionError.message === 'TimeoutError') {
throw this.connectionError
}
}
}
getBackoffTimedelta() {
if (!this.backoffTime) {
return 0
}
return (this.backoffTime - Date.now())
}
static sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
}

View File

@ -1,6 +1,9 @@
import coreIncludes from 'core-js/library/fn/array/includes'
import coreObjectEntries from 'core-js/library/fn/object/entries'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import 'core-js/features/array/includes'
import 'core-js/features/object/entries'
/**
* @private
@ -10,14 +13,14 @@ import coreObjectEntries from 'core-js/library/fn/object/entries'
*/
function filterFromObject(obj, filter, { isInclusion = true } = {}) {
if (filter && Array.isArray(filter)) {
return applyFilterOnObject(obj, isInclusion ? ((_, key) => coreIncludes(filter, key))
: ((_, key) => !coreIncludes(filter, key)))
return applyFilterOnObject(obj, isInclusion ? (val => filter.includes(val))
: (val => !filter.includes(val)))
} else if (filter && typeof filter === 'function') {
// Flip the filter fn's return if it's for inclusion
return applyFilterOnObject(obj, isInclusion ? filter
: (...args) => !filter(...args))
} else {
throw new Error('The given filter is not an array or function. Exclude aborted')
throw new Error('The given filter is not an array or function. Filter aborted')
}
}
@ -28,11 +31,11 @@ function filterFromObject(obj, filter, { isInclusion = true } = {}) {
*/
function applyFilterOnObject(obj, filterFn) {
if (filterFn == null) {
return Object.assign({}, obj)
return { ...obj }
}
const filteredObj = {}
coreObjectEntries(obj).forEach(([key, val]) => {
Object.entries(obj).forEach(([key, val]) => {
if (filterFn(val, key)) {
filteredObj[key] = val
}

View File

@ -1,8 +1,14 @@
import sha3 from 'js-sha3'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable camelcase */
import { sha3_256 } from 'js-sha3'
export default function sha256Hash(data) {
return sha3.sha3_256
return sha3_256
.create()
.update(data)
.hex()
}
/* eslint-enable camelcase */

View File

@ -1,8 +1,11 @@
import coreObjectEntries from 'core-js/library/fn/object/entries'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import 'core-js/features/object/entries'
import decamelize from 'decamelize'
import queryString from 'query-string'
/**
* @private
* imported from https://github.com/bigchaindb/js-utility-belt/
@ -34,7 +37,7 @@ export default function stringifyAsQueryParam(obj, transform = decamelize) {
return ''
}
const transformedKeysObj = coreObjectEntries(obj).reduce((paramsObj, [key, value]) => {
const transformedKeysObj = Object.entries(obj).reduce((paramsObj, [key, value]) => {
paramsObj[transform(key)] = value
return paramsObj
}, {})

View File

@ -1,8 +1,11 @@
import { Buffer } from 'buffer'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import stableStringify from 'json-stable-stringify'
import clone from 'clone'
import base58 from 'bs58'
import cc from 'crypto-conditions'
import { Ed25519Sha256, PreimageSha256, ThresholdSha256 } from 'crypto-conditions'
import ccJsonify from './utils/ccJsonify'
import sha256Hash from './sha256Hash'
@ -34,13 +37,13 @@ export default class Transaction {
static makeTransactionTemplate() {
const txTemplate = {
'id': null,
'operation': null,
'outputs': [],
'inputs': [],
'metadata': null,
'asset': null,
'version': '2.0',
id: null,
operation: null,
outputs: [],
inputs: [],
metadata: null,
asset: null,
version: '2.0',
}
return txTemplate
}
@ -75,7 +78,7 @@ export default class Transaction {
*/
static makeCreateTransaction(asset, metadata, outputs, ...issuers) {
const assetDefinition = {
'data': asset || null,
data: asset || null,
}
const inputs = issuers.map((issuer) => Transaction.makeInputTemplate([issuer]))
@ -90,16 +93,10 @@ export default class Transaction {
* @returns {Object} Ed25519 Condition (that will need to wrapped in an Output)
*/
static makeEd25519Condition(publicKey, json = true) {
const publicKeyBuffer = Buffer.from(base58.decode(publicKey))
const ed25519Fulfillment = new cc.Ed25519Sha256()
const publicKeyBuffer = base58.decode(publicKey)
const ed25519Fulfillment = new Ed25519Sha256()
ed25519Fulfillment.setPublicKey(publicKeyBuffer)
if (json) {
return ccJsonify(ed25519Fulfillment)
}
return ed25519Fulfillment
return json ? ccJsonify(ed25519Fulfillment) : ed25519Fulfillment
}
/**
@ -127,8 +124,8 @@ export default class Transaction {
getPublicKeys(condition.details)
return {
condition,
'amount': amount,
'public_keys': publicKeys,
amount,
public_keys: publicKeys,
}
}
@ -139,13 +136,9 @@ export default class Transaction {
* @returns {Object} Preimage-Sha256 Condition (that will need to wrapped in an Output)
*/
static makeSha256Condition(preimage, json = true) {
const sha256Fulfillment = new cc.PreimageSha256()
sha256Fulfillment.preimage = Buffer.from(preimage)
if (json) {
return ccJsonify(sha256Fulfillment)
}
return sha256Fulfillment
const sha256Fulfillment = new PreimageSha256()
sha256Fulfillment.setPreimage(Buffer.from(preimage))
return json ? ccJsonify(sha256Fulfillment) : sha256Fulfillment
}
/**
@ -156,19 +149,15 @@ export default class Transaction {
* @returns {Object} Sha256 Threshold Condition (that will need to wrapped in an Output)
*/
static makeThresholdCondition(threshold, subconditions = [], json = true) {
const thresholdCondition = new cc.ThresholdSha256()
thresholdCondition.threshold = threshold
const thresholdCondition = new ThresholdSha256()
thresholdCondition.setThreshold(threshold)
subconditions.forEach((subcondition) => {
// TODO: add support for Condition and URIs
// TODO: add support for Condition
thresholdCondition.addSubfulfillment(subcondition)
// ? Should be thresholdCondition.addSubcondition(subcondition)
})
if (json) {
return ccJsonify(thresholdCondition)
}
return thresholdCondition
return json ? ccJsonify(thresholdCondition) : thresholdCondition
}
/**
@ -201,15 +190,15 @@ export default class Transaction {
const { tx, outputIndex } = { tx: unspentOutput.tx, outputIndex: unspentOutput.output_index }
const fulfilledOutput = tx.outputs[outputIndex]
const transactionLink = {
'output_index': outputIndex,
'transaction_id': tx.id,
output_index: outputIndex,
transaction_id: tx.id,
}
return Transaction.makeInputTemplate(fulfilledOutput.public_keys, transactionLink)
})
const assetLink = {
'id': unspentOutputs[0].tx.operation === 'CREATE' ? unspentOutputs[0].tx.id
id: unspentOutputs[0].tx.operation === 'CREATE' ? unspentOutputs[0].tx.id
: unspentOutputs[0].tx.asset.id
}
return Transaction.makeTransaction('TRANSFER', assetLink, metadata, outputs, inputs)
@ -228,26 +217,71 @@ export default class Transaction {
*/
static signTransaction(transaction, ...privateKeys) {
const signedTx = clone(transaction)
const serializedTransaction =
Transaction.serializeTransactionIntoCanonicalString(transaction)
signedTx.inputs.forEach((input, index) => {
const privateKey = privateKeys[index]
const privateKeyBuffer = Buffer.from(base58.decode(privateKey))
const serializedTransaction =
Transaction.serializeTransactionIntoCanonicalString(transaction)
const privateKeyBuffer = base58.decode(privateKey)
const transactionUniqueFulfillment = input.fulfills ? serializedTransaction
.concat(input.fulfills.transaction_id)
.concat(input.fulfills.output_index) : serializedTransaction
const transactionHash = sha256Hash(transactionUniqueFulfillment)
const ed25519Fulfillment = new cc.Ed25519Sha256()
const ed25519Fulfillment = new Ed25519Sha256()
ed25519Fulfillment.sign(Buffer.from(transactionHash, 'hex'), privateKeyBuffer)
const fulfillmentUri = ed25519Fulfillment.serializeUri()
input.fulfillment = fulfillmentUri
})
const serializedTransaction =
const serializedSignedTransaction =
Transaction.serializeTransactionIntoCanonicalString(signedTx)
signedTx.id = sha256Hash(serializedTransaction)
signedTx.id = sha256Hash(serializedSignedTransaction)
return signedTx
}
/**
* Delegate signing of the given `transaction` returning a new copy of `transaction`
* that's been signed.
* @param {Object} transaction Transaction to sign. `transaction` is not modified.
* @param {Function} signFn Function signing the transaction, expected to return the fulfillment.
* @returns {Object} The signed version of `transaction`.
*/
static delegateSignTransaction(transaction, signFn) {
const signedTx = clone(transaction)
const serializedTransaction =
Transaction.serializeTransactionIntoCanonicalString(transaction)
signedTx.inputs.forEach((input, index) => {
const fulfillmentUri = signFn(serializedTransaction, input, index)
input.fulfillment = fulfillmentUri
})
const serializedSignedTransaction = Transaction.serializeTransactionIntoCanonicalString(signedTx)
signedTx.id = sha256Hash(serializedSignedTransaction)
return signedTx
}
/**
* Delegate signing of the given `transaction` returning a new copy of `transaction`
* that's been signed.
* @param {Object} transaction Transaction to sign. `transaction` is not modified.
* @param {Function} signFn Function signing the transaction, expected to resolve the fulfillment.
* @returns {Promise<Object>} The signed version of `transaction`.
*/
static async delegateSignTransactionAsync(transaction, signFn) {
const signedTx = clone(transaction)
const serializedTransaction =
Transaction.serializeTransactionIntoCanonicalString(transaction)
await Promise.all(signedTx.inputs.map(async (input, index) => {
const fulfillmentUri = await signFn(serializedTransaction, input, index)
input.fulfillment = fulfillmentUri
}))
const serializedSignedTransaction = Transaction.serializeTransactionIntoCanonicalString(signedTx)
signedTx.id = sha256Hash(serializedSignedTransaction)
return signedTx
}
}

64
src/transport.js Normal file
View File

@ -0,0 +1,64 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import Request from './request'
/**
*
* @private
* If initialized with ``>1`` nodes, the driver will send successive
* requests to different nodes in a round-robin fashion (this will be
* customizable in the future).
*/
export default class Transport {
constructor(nodes, timeout) {
this.connectionPool = []
this.timeout = timeout
// the maximum backoff time is 10 seconds
this.maxBackoffTime = timeout ? timeout / 2 : 10000
nodes.forEach(node => {
this.connectionPool.push(new Request(node))
})
}
// Select the connection with the earliest backoff time, in case of a tie,
// prefer the one with the smaller list index
pickConnection() {
let connection = this.connectionPool[0]
this.connectionPool.forEach(conn => {
// 0 the lowest value is the time for Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
conn.backoffTime = conn.backoffTime ? conn.backoffTime : 0
connection = (conn.backoffTime < connection.backoffTime) ? conn : connection
})
return connection
}
async forwardRequest(path, headers) {
let response
let connection
// A new request will be executed until there is a valid response or timeout < 0
while (this.timeout >= 0) {
connection = this.pickConnection()
// Date in milliseconds
const startTime = Date.now()
// eslint-disable-next-line no-await-in-loop
response = await connection.request(
path,
headers,
this.timeout,
this.maxBackoffTime
)
const elapsed = Date.now() - startTime
if (connection.backoffTime > 0 && this.timeout > 0) {
this.timeout -= elapsed
} else {
// No connection error, the response is valid
return response
}
}
throw new Error('TimeoutError')
}
}

View File

@ -1,6 +1,9 @@
import { Buffer } from 'buffer'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import base58 from 'bs58'
import cc from 'crypto-conditions'
import { Condition, Ed25519Sha256, ThresholdSha256 } from 'crypto-conditions'
/**
* Loads a crypto-condition class (Fulfillment or Condition) from a BigchainDB JSON object
@ -9,17 +12,18 @@ import cc from 'crypto-conditions'
*/
export default function ccJsonLoad(conditionJson) {
if ('hash' in conditionJson) {
const condition = new cc.Condition()
condition.type = conditionJson.type_id
condition.bitmask = conditionJson.bitmask
condition.hash = Buffer.from(base58.decode(conditionJson.hash))
const condition = new Condition()
condition.setTypeId(conditionJson.type_id)
condition.setSubtypes(conditionJson.bitmask)
condition.setHash(base58.decode(conditionJson.hash))
// TODO: fix this, maxFulfillmentLength cannot be set in CryptoCondition lib
condition.maxFulfillmentLength = parseInt(conditionJson.max_fulfillment_length, 10)
return condition
} else {
let fulfillment
if (conditionJson.type === 'threshold-sha-256') {
fulfillment = new cc.ThresholdSha256()
fulfillment = new ThresholdSha256()
fulfillment.threshold = conditionJson.threshold
conditionJson.subconditions.forEach((subconditionJson) => {
const subcondition = ccJsonLoad(subconditionJson)
@ -32,8 +36,8 @@ export default function ccJsonLoad(conditionJson) {
}
if (conditionJson.type === 'ed25519-sha-256') {
fulfillment = new cc.Ed25519Sha256()
fulfillment.publicKey = Buffer.from(base58.decode(conditionJson.public_key))
fulfillment = new Ed25519Sha256()
fulfillment.setPublicKey(base58.decode(conditionJson.public_key))
}
return fulfillment
}

View File

@ -1,3 +1,7 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import base58 from 'bs58'
/**
@ -15,8 +19,8 @@ export default function ccJsonify(fulfillment) {
}
const jsonBody = {
'details': {},
'uri': conditionUri,
details: {},
uri: conditionUri,
}
if (fulfillment.getTypeId() === 0) {
@ -31,15 +35,15 @@ export default function ccJsonify(fulfillment) {
if (fulfillment.getTypeId() === 2) {
return {
'details': {
'type': 'threshold-sha-256',
'threshold': fulfillment.threshold,
'subconditions': fulfillment.subconditions.map((subcondition) => {
details: {
type: 'threshold-sha-256',
threshold: fulfillment.threshold,
subconditions: fulfillment.subconditions.map((subcondition) => {
const subconditionJson = ccJsonify(subcondition.body)
return subconditionJson.details
})
},
'uri': conditionUri,
uri: conditionUri,
}
}

View File

@ -0,0 +1,30 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import rewire from 'rewire'
const baseRequestFile = rewire('../../src/baseRequest.js')
const baseRequest = baseRequestFile.__get__('baseRequest')
const handleResponse = baseRequestFile.__get__('handleResponse')
test('HandleResponse does not throw error for response ok', t => {
const testObj = {
ok: true
}
const expected = testObj
const actual = handleResponse(testObj)
t.deepEqual(actual, expected)
})
test('baseRequest test query and vsprint', async t => {
const error = await t.throwsAsync(baseRequest('https://%s.com/', {
urlTemplateSpec: ['google'],
query: 'teapot'
}), { instanceOf: Error, message: 'HTTP Error: Requested page not reachable' })
t.is(error.requestURI, 'https://www.google.com/teapot')
t.is(error.status, '418 I\'m a Teapot')
})

View File

@ -1,13 +1,20 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import sinon from 'sinon'
import * as request from '../../src/request' // eslint-disable-line
import { Connection } from '../../src'
import { API_PATH } from '../constants'
import {
Connection
} from '../../src'
import {
API_PATH
} from '../constants'
const conn = new Connection(API_PATH)
test('Payload thrown at incorrect API_PATH', t => {
test('Payload thrown at incorrect API_PATH', async t => {
const path = 'http://localhost:9984/api/wrong/'
const connection = new Connection(path)
const target = {
@ -15,10 +22,13 @@ test('Payload thrown at incorrect API_PATH', t => {
status: '404 NOT FOUND',
requestURI: 'http://localhost:9984/api/wrong/transactions/transactionId'
}
connection.getTransaction('transactionId')
.catch(error => {
t.deepEqual(target, error)
})
const error = await t.throwsAsync(connection.getTransaction('transactionId'), {
instanceOf: Error, message: target.message
})
t.is('ResponseError', error.name)
t.is(target.status, error.status)
t.is(target.requestURI, error.requestURI)
})
test('Generate API URLS', t => {
@ -27,41 +37,80 @@ test('Generate API URLS', t => {
'blocksDetail': 'blocks/%(blockHeight)s',
'outputs': 'outputs',
'transactions': 'transactions',
'transactionsSync': 'transactions?mode=sync',
'transactionsAsync': 'transactions?mode=async',
'transactionsCommit': 'transactions?mode=commit',
'transactionsDetail': 'transactions/%(transactionId)s',
'assets': 'assets',
}
Object.keys(endpoints).forEach(endpointName => {
const url = conn.getApiUrls(endpointName)
const expected = API_PATH + endpoints[endpointName]
const url = Connection.getApiUrls(endpointName)
const expected = endpoints[endpointName]
t.is(url, expected)
})
})
test('Request with custom headers', t => {
const testConn = new Connection(API_PATH, { hello: 'world' })
const expectedOptions = {
test('Normalize node from an object', t => {
const headers = {
custom: 'headers'
}
const node = {
endpoint: API_PATH,
headers: {
hello: 'world'
}
}
const expectedNode = {
'endpoint': API_PATH,
'headers': {
hello: 'world',
custom: 'headers'
}
}
// request is read only, cannot be mocked?
sinon.spy(request, 'default')
testConn._req(API_PATH, { headers: { custom: 'headers' } })
t.truthy(request.default.calledWith(API_PATH, expectedOptions))
request.default.restore()
t.deepEqual(Connection.normalizeNode(node, headers), expectedNode)
})
test('Normalize node from a string', t => {
const headers = {
custom: 'headers'
}
const expectedNode = {
'endpoint': API_PATH,
'headers': {
custom: 'headers'
}
}
t.deepEqual(Connection.normalizeNode(API_PATH, headers), expectedNode)
})
test('Request with custom headers', t => {
const testConn = new Connection(API_PATH, {
hello: 'world'
})
const expectedOptions = {
headers: {
custom: 'headers'
}
}
const PATH = 'blocks'
testConn.transport.forwardRequest = sinon.spy()
testConn._req(PATH, {
headers: {
custom: 'headers'
}
})
t.truthy(testConn.transport.forwardRequest.calledWith(PATH, expectedOptions))
})
test('Get block for a block id', t => {
const expectedPath = 'path'
const blockHeight = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.getBlock(blockHeight)
t.truthy(conn._req.calledWith(
@ -70,13 +119,12 @@ test('Get block for a block id', t => {
))
})
test('Get transaction for a transaction id', t => {
const expectedPath = 'path'
const transactionId = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.getTransaction(transactionId)
t.truthy(conn._req.calledWith(
@ -85,13 +133,12 @@ test('Get transaction for a transaction id', t => {
))
})
test('Get list of blocks for a transaction id', t => {
const expectedPath = 'path'
const transactionId = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.listBlocks(transactionId)
t.truthy(conn._req.calledWith(
@ -104,14 +151,13 @@ test('Get list of blocks for a transaction id', t => {
))
})
test('Get list of transactions for an asset id', t => {
const expectedPath = 'path'
const assetId = 'abc'
const operation = 'operation'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.listTransactions(assetId, operation)
t.truthy(conn._req.calledWith(
@ -125,13 +171,12 @@ test('Get list of transactions for an asset id', t => {
))
})
test('Get outputs for a public key and no spent flag', t => {
const expectedPath = 'path'
const publicKey = 'publicKey'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.listOutputs(publicKey)
t.truthy(conn._req.calledWith(
@ -140,14 +185,13 @@ test('Get outputs for a public key and no spent flag', t => {
))
})
test('Get outputs for a public key and spent=false', t => {
const expectedPath = 'path'
const publicKey = 'publicKey'
const spent = false
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.listOutputs(publicKey, spent)
t.truthy(conn._req.calledWith(
@ -156,14 +200,13 @@ test('Get outputs for a public key and spent=false', t => {
))
})
test('Get outputs for a public key and spent=true', t => {
const expectedPath = 'path'
const publicKey = 'publicKey'
const spent = true
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.listOutputs(publicKey, spent)
t.truthy(conn._req.calledWith(
@ -172,47 +215,30 @@ test('Get outputs for a public key and spent=true', t => {
))
})
test('Get votes for a block id', t => {
const expectedPath = 'path'
const blockId = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
conn.listVotes(blockId)
t.truthy(conn._req.calledWith(
expectedPath,
{ query: { block_id: blockId } }
))
})
test('Get asset for text', t => {
const expectedPath = 'path'
const search = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.searchAssets(search)
t.truthy(conn._req.calledWith(
expectedPath,
{ query: { search } }
{ query: { search, limit: 10 } }
))
})
test('Get metadata for text', t => {
const expectedPath = 'path'
const search = 'abc'
conn._req = sinon.spy()
conn.getApiUrls = sinon.stub().returns(expectedPath)
Connection.getApiUrls = sinon.stub().returns(expectedPath)
conn.searchMetadata(search)
t.truthy(conn._req.calledWith(
expectedPath,
{ query: { search } }
{ query: { search, limit: 10 } }
))
})

View File

@ -1,4 +1,10 @@
import test from 'ava'
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import { createHash } from 'crypto'
import base58 from 'bs58'
import { Ed25519Sha256 } from 'crypto-conditions'
import { Transaction, Ed25519Keypair } from '../src'
// TODO: Find out if ava has something like conftest, if so put this there.
@ -27,6 +33,21 @@ export const bob = new Ed25519Keypair()
export const bobCondition = Transaction.makeEd25519Condition(bob.publicKey)
export const bobOutput = Transaction.makeOutput(bobCondition)
export function delegatedSignTransaction(...keyPairs) {
return function sign(serializedTransaction, input) {
const transactionUniqueFulfillment = input.fulfills ? serializedTransaction
.concat(input.fulfills.transaction_id)
.concat(input.fulfills.output_index) : serializedTransaction
const transactionHash = createHash('sha3-256').update(transactionUniqueFulfillment).digest()
const filteredKeyPairs = keyPairs.filter(
({ publicKey }) => input.owners_before.includes(publicKey)
)
// TODO: https://github.com/avajs/ava/issues/1190
test('', () => 'dirty hack. TODO: Exclude this file from being run by ava')
const ed25519Fulfillment = new Ed25519Sha256()
filteredKeyPairs.forEach(keyPair => {
const privateKey = Buffer.from(base58.decode(keyPair.privateKey))
ed25519Fulfillment.sign(transactionHash, privateKey)
})
return ed25519Fulfillment.serializeUri()
}
}

View File

@ -1,3 +1,7 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import { Ed25519Keypair, Transaction, Connection } from '../../src'
@ -9,10 +13,10 @@ import {
bob,
bobOutput,
asset,
metaData
metaData,
delegatedSignTransaction
} from '../constants'
test('Keypair is created', t => {
const keyPair = new Ed25519Keypair()
@ -20,11 +24,24 @@ test('Keypair is created', t => {
t.truthy(keyPair.privateKey)
})
test('Valid CREATE transaction with default node', t => {
const conn = new Connection()
// TODO: The following tests are a bit messy currently, please do:
//
// - tidy up dependency on `pollStatusAndFetchTransaction`
test('Valid CREATE transaction', t => {
const tx = Transaction.makeCreateTransaction(
asset(),
metaData,
[aliceOutput],
alice.publicKey
)
const txSigned = Transaction.signTransaction(tx, alice.privateKey)
return conn.postTransaction(txSigned)
.then(resTx => {
t.truthy(resTx)
})
})
test('Valid CREATE transaction using async', t => {
const conn = new Connection(API_PATH)
const tx = Transaction.makeCreateTransaction(
@ -35,10 +52,24 @@ test('Valid CREATE transaction', t => {
)
const txSigned = Transaction.signTransaction(tx, alice.privateKey)
return conn.postTransactionCommit(txSigned)
return conn.postTransactionAsync(txSigned)
.then(resTx => t.truthy(resTx))
})
test('Valid CREATE transaction using sync', t => {
const conn = new Connection(API_PATH)
const tx = Transaction.makeCreateTransaction(
asset(),
metaData,
[aliceOutput],
alice.publicKey
)
const txSigned = Transaction.signTransaction(tx, alice.privateKey)
return conn.postTransactionSync(txSigned)
.then(resTx => t.truthy(resTx))
})
test('Valid TRANSFER transaction with single Ed25519 input', t => {
const conn = new Connection(API_PATH)
@ -69,7 +100,6 @@ test('Valid TRANSFER transaction with single Ed25519 input', t => {
})
})
test('Valid TRANSFER transaction with multiple Ed25519 inputs', t => {
const conn = new Connection(API_PATH)
const createTx = Transaction.makeCreateTransaction(
@ -100,7 +130,6 @@ test('Valid TRANSFER transaction with multiple Ed25519 inputs', t => {
})
})
test('Valid TRANSFER transaction with multiple Ed25519 inputs from different transactions', t => {
const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair()
@ -145,7 +174,7 @@ test('Valid TRANSFER transaction with multiple Ed25519 inputs from different tra
)
return conn.postTransactionCommit(transferTxSigned1)
.then(conn.postTransactionCommit(transferTxSigned2))
.then(() => conn.postTransactionCommit(transferTxSigned2))
.then(() => {
const transferTxMultipleInputs = Transaction.makeTransferTransaction(
[{ tx: transferTxSigned1, output_index: 0 },
@ -164,6 +193,58 @@ test('Valid TRANSFER transaction with multiple Ed25519 inputs from different tra
})
})
test('Valid CREATE transaction using delegateSign with default node', t => {
const conn = new Connection()
const tx = Transaction.makeCreateTransaction(
asset(),
metaData,
[aliceOutput],
alice.publicKey
)
const txSigned = Transaction.delegateSignTransaction(
tx,
delegatedSignTransaction(alice)
)
return conn.postTransaction(txSigned)
.then(resTx => {
t.truthy(resTx)
})
})
test('Valid TRANSFER transaction with multiple Ed25519 inputs using delegateSign', t => {
const conn = new Connection(API_PATH)
const createTx = Transaction.makeCreateTransaction(
asset(),
metaData,
[aliceOutput, bobOutput],
alice.publicKey
)
const createTxSigned = Transaction.signTransaction(
createTx,
alice.privateKey
)
return conn.postTransactionCommit(createTxSigned)
.then(() => {
const transferTx = Transaction.makeTransferTransaction(
[{ tx: createTxSigned, output_index: 0 }, { tx: createTxSigned, output_index: 1 }],
[Transaction.makeOutput(aliceCondition, '2')],
metaData
)
const transferTxSigned = Transaction.delegateSignTransaction(
transferTx,
delegatedSignTransaction(alice, bob)
)
return conn.postTransactionCommit(transferTxSigned)
.then(resTx => t.truthy(resTx))
})
})
test('Search for spent and unspent outputs of a given public key', t => {
const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair()
@ -173,7 +254,6 @@ test('Search for spent and unspent outputs of a given public key', t => {
const trentCondition = Transaction.makeEd25519Condition(trent.publicKey)
const trentOutput = Transaction.makeOutput(trentCondition)
const createTx = Transaction.makeCreateTransaction(
asset(),
metaData,
@ -204,7 +284,6 @@ test('Search for spent and unspent outputs of a given public key', t => {
.then(outputs => t.truthy(outputs.length === 2))
})
test('Search for unspent outputs for a given public key', t => {
const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair()
@ -244,7 +323,6 @@ test('Search for unspent outputs for a given public key', t => {
.then(outputs => t.truthy(outputs.length === 2))
})
test('Search for spent outputs for a given public key', t => {
const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair()
@ -284,7 +362,6 @@ test('Search for spent outputs for a given public key', t => {
.then(outputs => t.truthy(outputs.length === 1))
})
test('Search for an asset', t => {
const conn = new Connection(API_PATH)
@ -307,7 +384,6 @@ test('Search for an asset', t => {
))
})
test('Search for metadata', t => {
const conn = new Connection(API_PATH)
@ -330,7 +406,6 @@ test('Search for metadata', t => {
))
})
test('Search blocks containing a transaction', t => {
const conn = new Connection(API_PATH)
@ -352,7 +427,6 @@ test('Search blocks containing a transaction', t => {
.then(transactions => t.truthy(transactions.length === 1))
})
test('Search transaction containing an asset', t => {
const conn = new Connection(API_PATH)
@ -374,7 +448,8 @@ test('Search transaction containing an asset', t => {
})
})
test('Content-Type cannot be set', t => {
t.throws(() => new Connection(API_PATH, { 'Content-Type': 'application/json' }), Error)
t.throws(() => new Connection(API_PATH, { 'Content-Type': 'application/json' }), {
instanceOf: Error
})
})

View File

@ -0,0 +1,26 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import Connection from '../../src/connection'
const conn = new Connection()
test('Ensure that BackoffTimedelta works properly', t => {
const req = conn.transport.pickConnection()
req.backoffTime = Date.now() + 50
const target = req.getBackoffTimedelta()
// The value should be close to 50
t.is(target > 45, true)
})
test('Ensure that updateBackoffTime throws and error on TimeoutError', async t => {
const req = conn.transport.pickConnection()
const errorMessage = 'TimeoutError'
req.connectionError = new Error(errorMessage)
t.throws(() => {
req.updateBackoffTime()
}, { instanceOf: Error, message: errorMessage })
})

View File

@ -0,0 +1,55 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import rewire from 'rewire'
const sanitize = rewire('../../src/sanitize.js')
const applyFilterOnObject = sanitize.__get__('applyFilterOnObject')
const filterFromObject = sanitize.__get__('filterFromObject')
test('Ensure that null filter returns same object', t => {
const expected = { 'testObj': 'test' }
const actual = applyFilterOnObject({ 'testObj': 'test' }, null)
t.deepEqual(actual, expected)
})
test('Ensure function filter with isInclusion true works properly', t => {
const testObj = [true, false, undefined, '', 0, null]
const expected = { 0: true }
const actual = filterFromObject(testObj, (val) => !!val, { isInclusion: true })
t.deepEqual(actual, expected)
})
test('Ensure function filter with isInclusion false works properly', t => {
const testObj = [false, true, 1, 10, 'this will be removed as it is truthy']
const expected = { 0: false }
const actual = filterFromObject(testObj, (val) => !!val, { isInclusion: false })
t.deepEqual(actual, expected)
})
test('Ensure array filter with isInclusion true works properly', t => {
const testObj = [true, false, undefined, '', 0, null]
const expected = { 0: true }
const actual = filterFromObject(testObj, [true], { isInclusion: true })
t.deepEqual(actual, expected)
})
test('Ensure array filter with isInclusion false works properly', t => {
const testObj = [false, true, 1, 10]
const expected = { 0: false }
const actual = filterFromObject(testObj, [true, 1, 10], { isInclusion: false })
t.deepEqual(actual, expected)
})
test('Ensure throws error when given invalid filter', t => {
t.throws(() => {
filterFromObject({}, 'lol')
}, { instanceOf: Error, message: 'The given filter is not an array or function. Filter aborted' })
})

View File

@ -0,0 +1,50 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import formatText from '../../src/format_text'
test('formatText test type 1', t => {
const expected = 'Hi there Dimi!'
const actual = formatText('Hi there ${dimi}!', { dimi: 'Dimi' }) // eslint-disable-line no-template-curly-in-string
t.is(actual, expected)
})
test('formatText test type 2', t => {
const expected = 'BigchainDB is big'
const actual = formatText('${database} is %(status)s', { // eslint-disable-line no-template-curly-in-string
database: 'BigchainDB',
status: 'big'
})
t.is(actual, expected)
})
test('formatText test type 3', t => {
const expected = 'Berlin is best known for its Currywurst'
const actual = formatText(
'Berlin is best known for its ${berlin.topKnownFor[0].name}', // eslint-disable-line no-template-curly-in-string
{
berlin: {
topKnownFor: [
{
name: 'Currywurst'
}
]
}
}
)
t.is(actual, expected)
})
test('formatText test throws', t => {
t.throws(() => {
formatText(
'This will give ${error.}', // eslint-disable-line no-template-curly-in-string
{ error: [{}] }
)
}, { instanceOf: SyntaxError, message: '[formatText] failed to parse named argument key: error.' })
})

View File

@ -1,6 +1,13 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import { createHash } from 'crypto'
import { validateFulfillment } from 'crypto-conditions'
import test from 'ava'
import cc from 'crypto-conditions'
import base58 from 'bs58'
import { Ed25519Keypair, Transaction, ccJsonLoad } from '../../src'
import { delegatedSignTransaction } from '../constants'
import sha256Hash from '../../src/sha256Hash'
test('Ed25519 condition encoding', t => {
@ -29,7 +36,6 @@ test('Sha256Condition fulfillment', t => {
t.deepEqual(target, Transaction.makeSha256Condition(preimage))
})
test('Threshold condition encoding', t => {
const publicKey = '4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS'
const ed25519 = Transaction.makeEd25519Condition(publicKey, false)
@ -59,7 +65,6 @@ test('Threshold condition encoding', t => {
t.deepEqual(target, output)
})
test('Fulfillment correctly formed', t => {
const alice = new Ed25519Keypair()
const txCreate = Transaction.makeCreateTransaction(
@ -86,39 +91,60 @@ test('Fulfillment correctly formed', t => {
.concat(txTransfer.inputs[0].fulfills.output_index) : msg
const msgHash = sha256Hash(msgUniqueFulfillment)
t.truthy(cc.validateFulfillment(
txSigned.inputs[0].fulfillment, txCreate.outputs[0].condition.uri,
t.truthy(validateFulfillment(
txSigned.inputs[0].fulfillment,
txCreate.outputs[0].condition.uri,
Buffer.from(msgHash, 'hex')
))
})
test('Delegated signature is correct', t => {
const alice = new Ed25519Keypair()
const txCreate = Transaction.makeCreateTransaction(
{},
{},
[Transaction.makeOutput(Transaction.makeEd25519Condition(alice.publicKey))],
alice.publicKey
)
const signCreateTransaction = Transaction.signTransaction(txCreate, alice.privateKey)
const delegatedSignCreateTransaction = Transaction.delegateSignTransaction(
txCreate,
delegatedSignTransaction(alice)
)
t.deepEqual(signCreateTransaction, delegatedSignCreateTransaction)
})
test('Delegated async signature is correct', async t => {
const alice = new Ed25519Keypair()
const txCreate = Transaction.makeCreateTransaction(
{},
{},
[Transaction.makeOutput(Transaction.makeEd25519Condition(alice.publicKey))],
alice.publicKey
)
const signCreateTransaction = Transaction.signTransaction(txCreate, alice.privateKey)
const delegatedSignCreateTransaction = await Transaction.delegateSignTransactionAsync(
txCreate,
delegatedSignTransaction(alice)
)
t.deepEqual(signCreateTransaction, delegatedSignCreateTransaction)
})
test('CryptoConditions JSON load', t => {
const publicKey = '4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS'
const cond = ccJsonLoad({
type: 'threshold-sha-256',
threshold: 1,
subconditions: [{
type: 'ed25519-sha-256',
public_key: 'a'
public_key: publicKey
},
{
hash: 'a'
}],
})
t.truthy(cond.subconditions.length === 2)
})
test('CryptoConditions JSON load', t => {
const cond = ccJsonLoad({
type: 'threshold-sha-256',
threshold: 1,
subconditions: [{
type: 'ed25519-sha-256',
public_key: 'a'
},
{
hash: 'a'
hash: base58.encode(createHash('sha256').update('a').digest())
}],
})
t.truthy(cond.subconditions.length === 2)

View File

@ -1,3 +1,7 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import sinon from 'sinon'
@ -11,7 +15,6 @@ import {
transferTx
} from '../constants'
test('Create valid output with default amount', t => {
const condition = {
details: {
@ -28,7 +31,6 @@ test('Create valid output with default amount', t => {
t.deepEqual(res, expected)
})
test('Create valid output with custom amount', t => {
const condition = {
details: {
@ -61,12 +63,10 @@ test('Pass condition not based on public_keys to makeOutput', t => {
t.deepEqual(res, expected)
})
test('makeOutput throws TypeError with incorrect amount type', t => {
t.throws(() => Transaction.makeOutput({}, 1337), TypeError)
t.throws(() => Transaction.makeOutput({}, 1337), { instanceOf: TypeError })
})
test('Create TRANSFER transaction based on CREATE transaction', t => {
sinon.spy(Transaction, 'makeTransaction')
Transaction.makeTransferTransaction(
@ -91,7 +91,6 @@ test('Create TRANSFER transaction based on CREATE transaction', t => {
Transaction.makeTransaction.restore()
})
test('Create TRANSFER transaction based on TRANSFER transaction', t => {
sinon.spy(Transaction, 'makeTransaction')

View File

@ -0,0 +1,23 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava'
import {
Connection
} from '../../src'
test('Pick connection with earliest backoff time', async t => {
const path1 = 'http://localhost:9984/api/v1/'
const path2 = 'http://localhostwrong:9984/api/v1/'
// Reverse order
const conn = new Connection([path2, path1])
// This will trigger the 'forwardRequest' so the correct connection will be taken
await conn.searchAssets('example')
const connection1 = conn.transport.connectionPool[1]
t.deepEqual(conn.transport.pickConnection(), connection1)
})

10
types/Ed25519Keypair.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
export default class Ed25519Keypair {
publicKey: string;
privateKey: string;
constructor(seed?: Buffer);
}

31
types/baseRequest.d.ts vendored Normal file
View File

@ -0,0 +1,31 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
export interface RequestConfig {
headers?: Record<string, string | string[]>;
jsonBody?: Record<string, any>;
query?: Record<string, any>;
method?: 'GET' | ' POST' | 'PUT';
urlTemplateSpec?: any[] | Record<string, any>;
[key: string]: any;
}
export function ResponseError(
message: string,
status?: number,
requestURI?: string
): void;
declare function timeout<T = Response>(
ms: number,
promise: Promise<T>
): Promise<T>;
declare function handleResponse(res: Response): Response;
export default function baseRequest(
url: string,
config: RequestConfig,
requestTimeout?: number
): Promise<Response>;

179
types/connection.d.ts vendored Normal file
View File

@ -0,0 +1,179 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import type { RequestConfig } from './baseRequest';
import type { Node } from './request';
import type Transport from './transport';
import type {
CreateTransaction,
TransactionOperations,
TransferTransaction,
TransactionCommon,
} from './transaction';
declare const DEFAULT_NODE = 'http://localhost:9984/api/v1/';
declare const DEFAULT_TIMEOUT = 20000; // The default value is 20 seconds
export interface InputNode {
endpoint: string;
}
export type AssetResult = {
id: string;
data: Record<string, any>;
};
export type MetadataResult = {
id: string;
metadata: Record<string, any>;
};
export enum Endpoints {
blocks = 'blocks',
blocksDetail = 'blocksDetail',
outputs = 'outputs',
transactions = 'transactions',
transactionsSync = 'transactionsSync',
transactionsAsync = 'transactionsAsync',
transactionsCommit = 'transactionsCommit',
transactionsDetail = 'transactionsDetail',
assets = 'assets',
metadata = 'metadata',
}
export interface EndpointsUrl {
[Endpoints.blocks]: 'blocks';
[Endpoints.blocksDetail]: 'blocks/%(blockHeight)s';
[Endpoints.outputs]: 'outputs';
[Endpoints.transactions]: 'transactions';
[Endpoints.transactionsSync]: 'transactions?mode=sync';
[Endpoints.transactionsAsync]: 'transactions?mode=async';
[Endpoints.transactionsCommit]: 'transactions?mode=commit';
[Endpoints.transactionsDetail]: 'transactions/%(transactionId)s';
[Endpoints.assets]: 'assets';
[Endpoints.metadata]: 'metadata';
}
export interface EndpointsResponse<
O = TransactionOperations.CREATE,
A = Record<string, any>,
M = Record<string, any>
> {
[Endpoints.blocks]: number[];
[Endpoints.blocksDetail]: {
height: number;
transactions: (CreateTransaction | TransferTransaction)[];
};
[Endpoints.outputs]: {
transaction_id: string;
output_index: number;
}[];
[Endpoints.transactions]: O extends TransactionOperations.CREATE
? CreateTransaction[]
: O extends TransactionOperations.TRANSFER
? TransferTransaction[]
: (CreateTransaction | TransferTransaction)[];
[Endpoints.transactionsSync]: O extends TransactionOperations.CREATE
? CreateTransaction<A, M>
: TransferTransaction<M>;
[Endpoints.transactionsAsync]: O extends TransactionOperations.CREATE
? CreateTransaction<A, M>
: TransferTransaction<M>;
[Endpoints.transactionsCommit]: O extends TransactionOperations.CREATE
? CreateTransaction<A, M>
: TransferTransaction<M>;
[Endpoints.transactionsDetail]: O extends TransactionOperations.CREATE
? CreateTransaction<A, M>
: TransferTransaction<M>;
[Endpoints.assets]: AssetResult[];
[Endpoints.metadata]: MetadataResult[];
}
export default class Connection {
private transport: Transport;
private normalizedNodes: Node[];
private headers: Record<string, string | string[]>;
constructor(
nodes: string | InputNode | (string | InputNode)[],
headers?: Record<string, string | string[]>,
timeout?: number
);
static normalizeNode(
node: string | InputNode,
headers: Record<string, string | string[]>
): Node;
static getApiUrls<E extends keyof EndpointsUrl>(endpoint: E): EndpointsUrl[E];
private _req<E extends keyof EndpointsUrl, O = Record<string, any>>(
path: EndpointsUrl[E],
options: RequestConfig
): Promise<O>;
getBlock(
blockHeight: number | string
): Promise<EndpointsResponse[Endpoints.blocksDetail]>;
getTransaction<O = TransactionOperations.CREATE>(
transactionId: string
): Promise<EndpointsResponse<O>[Endpoints.transactionsDetail]>;
listBlocks(
transactionId: string
): Promise<EndpointsResponse[Endpoints.blocks]>;
listOutputs(
publicKey: string,
spent?: boolean
): Promise<EndpointsResponse[Endpoints.outputs]>;
listTransactions(
assetId: string,
operation?: TransactionOperations
): Promise<EndpointsResponse<typeof operation>[Endpoints.transactions]>;
postTransaction<
O extends TransactionOperations = TransactionOperations.CREATE,
A = Record<string, any>,
M = Record<string, any>
>(
transaction: TransactionCommon<O>
): Promise<EndpointsResponse<O, A, M>[Endpoints.transactionsCommit]>;
postTransactionSync<
O extends TransactionOperations = TransactionOperations.CREATE,
A = Record<string, any>,
M = Record<string, any>
>(
transaction: TransactionCommon<O>
): Promise<EndpointsResponse<O, A, M>[Endpoints.transactionsSync]>;
postTransactionAsync<
O extends TransactionOperations = TransactionOperations.CREATE,
A = Record<string, any>,
M = Record<string, any>
>(
transaction: TransactionCommon<O>
): Promise<EndpointsResponse<O, A, M>[Endpoints.transactionsAsync]>;
postTransactionCommit<
O extends TransactionOperations = TransactionOperations.CREATE,
A = Record<string, any>,
M = Record<string, any>
>(
transaction: TransactionCommon<O>
): Promise<EndpointsResponse<O, A, M>[Endpoints.transactionsCommit]>;
searchAssets(
search: string,
limit?: number
): Promise<EndpointsResponse[Endpoints.assets]>;
searchMetadata(
search: string,
limit?: number
): Promise<EndpointsResponse[Endpoints.metadata]>;
}

39
types/index.d.ts vendored Normal file
View File

@ -0,0 +1,39 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import Ed25519Keypair from './Ed25519Keypair';
import Connection, {
Endpoints,
EndpointsResponse,
EndpointsUrl,
} from './connection';
import Transaction, {
CreateTransaction,
TransactionCommon,
TransactionCommonSigned,
TransactionInput,
TransactionOutput,
TransferTransaction,
TransactionUnspentOutput,
TransactionOperations,
} from './transaction';
import ccJsonLoad from './utils/ccJsonLoad';
import ccJsonify from './utils/ccJsonify';
export { ccJsonLoad, ccJsonify, Connection, Ed25519Keypair, Transaction };
// Extras
export {
Endpoints,
EndpointsResponse,
EndpointsUrl,
CreateTransaction,
TransactionCommon,
TransactionCommonSigned,
TransactionInput,
TransactionOutput,
TransferTransaction,
TransactionUnspentOutput,
TransactionOperations,
};

32
types/request.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import type { RequestConfig } from './baseRequest';
export interface Node {
endpoint: string;
headers: Record<string, string | string[]>;
}
export default class Request {
private node: Node;
private backoffTime: number;
private retries: number;
private connectionError?: Error;
constructor(node: Node);
request<O = Record<string, any>>(
urlPath: string,
config?: RequestConfig,
timeout?: number,
maxBackoffTime?: number
): Promise<O>;
updateBackoffTime(maxBackoffTime: number): void;
getBackoffTimedelta(): number;
static sleep(ms: number): void;
}

25
types/sanitize.d.ts vendored Normal file
View File

@ -0,0 +1,25 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
declare type FilterFn = (val: any, key?: string) => void;
declare function filterFromObject<I = Record<string, any>>(
obj: I,
filter: Array<any> | FilterFn,
conf: { isInclusion?: boolean }
): Partial<I>;
declare function applyFilterOnObject<I = Record<string, any>>(
obj: I,
filterFn?: FilterFn
): Partial<I>;
declare function selectFromObject<I = Record<string, any>>(
obj: I,
filter: Array<any> | FilterFn
): Partial<I>;
export default function sanitize<I = Record<string, any>>(
obj: I
): Partial<I> | I;

236
types/transaction.d.ts vendored Normal file
View File

@ -0,0 +1,236 @@
import type {
Ed25519Sha256,
Fulfillment,
PreimageSha256,
ThresholdSha256,
} from 'crypto-conditions';
import {
Ed25519Sha256JSONCondition,
PreimageSha256JSONCondition,
ThresholdSha256JSONCondition,
} from './utils/ccJsonify';
export interface TransactionInput {
fulfillment: string;
fulfills: {
output_index: number;
transaction_id: string;
} | null;
owners_before: string[];
}
export interface TransactionOutput {
amount: string;
condition:
| PreimageSha256JSONCondition
| ThresholdSha256JSONCondition
| Ed25519Sha256JSONCondition;
public_keys: string[];
}
export enum TransactionOperations {
CREATE = 'CREATE',
TRANSFER = 'TRANSFER',
}
export interface TransactionCommon<
O extends TransactionOperations = TransactionOperations.CREATE,
A extends Record<string, any> = Record<string, unknown>,
M extends Record<string, any> = Record<string, unknown>
> {
id?: string;
inputs: TransactionInput[];
outputs: TransactionOutput[];
version: string;
metadata: M;
operation: O;
asset: TransactionAssetMap<O, A>;
}
export interface TransactionCommonSigned<
O extends TransactionOperations = TransactionOperations.CREATE,
A extends Record<string, any> = Record<string, unknown>,
M extends Record<string, any> = Record<string, unknown>
> extends Omit<TransactionCommon<O, A, M>, 'id'> {
id: string;
}
export type TransactionAssetMap<
Operation,
A extends Record<string, any>
> = Operation extends TransactionOperations.CREATE
? {
data: A;
}
: {
id: string;
};
export interface CreateTransaction<
A extends Record<string, any> = Record<string, unknown>,
M extends Record<string, any> = Record<string, unknown>
> extends TransactionCommon<TransactionOperations.CREATE, A, M> {
id: string;
asset: TransactionAssetMap<TransactionOperations.CREATE, A>;
operation: TransactionOperations.CREATE;
}
export interface TransferTransaction<
M extends Record<string, any> = Record<string, unknown>
> extends TransactionCommon<TransactionOperations.TRANSFER, any, M> {
id: string;
asset: TransactionAssetMap<TransactionOperations.TRANSFER, { id: string }>;
operation: TransactionOperations.TRANSFER;
}
export interface TransactionUnspentOutput {
tx: TransactionCommon;
output_index: number;
}
interface TxTemplate {
id: null;
operation: null;
outputs: [];
inputs: [];
metadata: null;
asset: null;
version: '2.0';
}
export type DelegateSignFunction = (
serializedTransaction: string,
input: TransactionInput,
index?: number
) => string;
export type DelegateSignFunctionAsync = (
serializedTransaction: string,
input: TransactionInput,
index?: number
) => Promise<string>;
export default class Transaction {
static serializeTransactionIntoCanonicalString<
O extends TransactionOperations = TransactionOperations
>(transaction: TransactionCommon<O>): string;
static serializeTransactionIntoCanonicalString(
transaction: CreateTransaction | TransferTransaction
): string;
static makeEd25519Condition(publicKey: string): Ed25519Sha256JSONCondition;
static makeEd25519Condition(
publicKey: string,
json: true
): Ed25519Sha256JSONCondition;
static makeEd25519Condition(publicKey: string, json: false): Ed25519Sha256;
static makeEd25519Condition(
publicKey: string,
json?: boolean
): Ed25519Sha256 | Ed25519Sha256JSONCondition;
static makeSha256Condition(preimage: string): PreimageSha256JSONCondition;
static makeSha256Condition(
preimage: string,
json: true
): PreimageSha256JSONCondition;
static makeSha256Condition(preimage: string, json: false): PreimageSha256;
static makeSha256Condition(
preimage: string,
json?: boolean
): PreimageSha256 | PreimageSha256JSONCondition;
static makeThresholdCondition(
threshold: number,
subconditions: (string | Fulfillment)[]
): ThresholdSha256JSONCondition;
static makeThresholdCondition(
threshold: number,
subconditions: (string | Fulfillment)[],
json: true
): ThresholdSha256JSONCondition;
static makeThresholdCondition(
threshold: number,
subconditions: (string | Fulfillment)[],
json: false
): ThresholdSha256;
static makeThresholdCondition(
threshold: number,
subconditions: (string | Fulfillment)[],
json?: boolean
): ThresholdSha256 | ThresholdSha256JSONCondition;
static makeInputTemplate(
publicKeys: string[],
fulfills?: TransactionInput['fulfills'],
fulfillment?: TransactionInput['fulfillment']
): TransactionInput;
static makeOutput(
condition:
| PreimageSha256JSONCondition
| ThresholdSha256JSONCondition
| Ed25519Sha256JSONCondition,
amount?: string
): TransactionOutput;
static makeTransactionTemplate(): TxTemplate;
static makeTransaction<
O extends TransactionOperations,
A = Record<string, any>,
M = Record<string, any>
>(
operation: O,
asset: A,
metadata: M,
outputs: TransactionOutput[],
inputs: TransactionInput[]
): TransactionCommon<O, A, M>;
static makeCreateTransaction<
A = Record<string, any>,
M = Record<string, any>
>(
asset: A,
metadata: M,
outputs: TransactionOutput[],
...issuers: string[]
): CreateTransaction<A, M>;
static makeTransferTransaction<M = Record<string, any>>(
unspentOutputs: TransactionUnspentOutput[],
outputs: TransactionOutput[],
metadata: M
): TransferTransaction<M>;
static signTransaction<
O extends TransactionOperations = TransactionOperations.CREATE
>(
transaction: TransactionCommon<O>,
...privateKeys: string[]
): TransactionCommonSigned<O>;
static delegateSignTransaction<
O extends TransactionOperations = TransactionOperations.CREATE
>(
transaction: TransactionCommon<O>,
signFn: DelegateSignFunction
): TransactionCommonSigned<O>;
static delegateSignTransactionAsync<
O extends TransactionOperations = TransactionOperations.CREATE
>(
transaction: TransactionCommon<O>,
signFn: DelegateSignFunctionAsync
): Promise<TransactionCommonSigned<O>>;
}

21
types/transport.d.ts vendored Normal file
View File

@ -0,0 +1,21 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import Request, { Node } from './request';
import type { RequestConfig } from './baseRequest';
export default class Transport {
private connectionPool: Request[];
private timeout: number;
private maxBackoffTime: number;
constructor(nodes: Node[], timeout: number);
pickConnection(): Request;
forwardRequest<O = Record<string, any>>(
path: string,
config: RequestConfig
): Promise<O>;
}

32
types/utils/ccJsonLoad.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import type {
Condition,
Ed25519Sha256,
PreimageSha256,
ThresholdSha256,
} from 'crypto-conditions';
import type {
Ed25519Sha256JSONCondition,
JSONCondition,
PreimageSha256JSONCondition,
ThresholdSha256JSONCondition,
} from './ccJsonify';
declare function ccJsonLoad(
conditionJson: PreimageSha256JSONCondition
): PreimageSha256;
declare function ccJsonLoad(
conditionJson: ThresholdSha256JSONCondition
): ThresholdSha256;
declare function ccJsonLoad(
conditionJson: Ed25519Sha256JSONCondition
): Ed25519Sha256;
declare function ccJsonLoad(conditionJson: JSONCondition): Condition;
export default ccJsonLoad;

70
types/utils/ccJsonify.d.ts vendored Normal file
View File

@ -0,0 +1,70 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import type {
Condition,
Ed25519Sha256,
PreimageSha256,
ThresholdSha256,
} from 'crypto-conditions';
import type { TypeId, TypeName } from 'crypto-conditions/types/types';
interface BaseJSONCondition {
details: {
[key: string]: any;
};
uri: string;
}
export interface JSONCondition extends BaseJSONCondition {
details: {
type_id: TypeId;
bitmask: number;
type: 'condition';
hash: string;
max_fulfillment_length: number;
};
}
export interface PreimageSha256JSONCondition extends BaseJSONCondition {
details: {
type_id: TypeId.PreimageSha256;
bitmask: 3;
preimage?: string;
type?: 'fulfillement';
};
}
export interface ThresholdSha256JSONCondition extends BaseJSONCondition {
details: {
type: TypeName.ThresholdSha256;
subConditions: (Ed25519Sha256JSONCondition | PreimageSha256JSONCondition)[];
};
}
export interface Ed25519Sha256JSONCondition extends BaseJSONCondition {
details: { type: TypeName.Ed25519Sha256; publicKey?: string };
}
export type JSONConditionUnion =
| JSONCondition
| PreimageSha256JSONCondition
| ThresholdSha256JSONCondition
| Ed25519Sha256JSONCondition;
declare function ccJsonify(
fulfillment: PreimageSha256
): PreimageSha256JSONCondition;
declare function ccJsonify(
fulfillment: ThresholdSha256
): ThresholdSha256JSONCondition;
declare function ccJsonify(
fulfillment: Ed25519Sha256
): Ed25519Sha256JSONCondition;
declare function ccJsonify(fulfillment: Condition): JSONCondition;
export default ccJsonify;

42
webpack.common.js Normal file
View File

@ -0,0 +1,42 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand */
'use strict'
const { ProvidePlugin } = require('webpack')
const { paths } = require('./webpack.parts')
module.exports = {
entry: paths.entry,
mode: 'none',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
}
]
},
optimization: {
minimize: true,
emitOnErrors: false
},
resolve: {
extensions: ['.js'],
modules: ['node_modules'],
fallback: {
buffer: require.resolve('buffer/'),
}
},
plugins: [
new ProvidePlugin({
Buffer: ['buffer', 'Buffer']
})
]
}

View File

@ -1,113 +1,34 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand */
'use strict'
const path = require('path')
const webpack = require('webpack')
const PRODUCTION = process.env.NODE_ENV === 'production'
const PATHS = {
ENTRY: path.resolve(__dirname, './src/index.js'),
BUNDLE: path.resolve(__dirname, 'dist/browser'),
NODE_MODULES: path.resolve(__dirname, 'node_modules'),
const common = require('./webpack.common')
const { outputs } = require('./webpack.parts')
// '[libraryTarget]': [file extension]
const OUTPUT_MAPPING = {
'amd': 'amd',
'commonjs': 'cjs',
'commonjs2': 'cjs2',
'umd': 'umd',
'window': 'window',
}
const OUTPUTS = [
{
filename: PRODUCTION ? 'bigchaindb-driver.window.min.js' : 'bigchaindb-driver.window.js',
library: 'BigchainDB',
libraryTarget: 'window',
path: PATHS.BUNDLE,
},
{
filename: PRODUCTION ? 'bigchaindb-driver.umd.min.js' : 'bigchaindb-driver.umd.js',
library: 'bigchaindb-driver',
libraryTarget: 'umd',
path: PATHS.BUNDLE,
},
{
filename: PRODUCTION ? 'bigchaindb-driver.cjs.min.js' : 'bigchaindb-driver.cjs.js',
library: 'bigchaindb-driver',
libraryTarget: 'commonjs',
path: PATHS.BUNDLE,
},
{
filename: PRODUCTION ? 'bigchaindb-driver.cjs2.min.js' : 'bigchaindb-driver.cjs2.js',
library: 'bigchaindb-driver',
libraryTarget: 'commonjs2',
path: PATHS.BUNDLE,
},
{
filename: PRODUCTION ? 'bigchaindb-driver.amd.min.js' : 'bigchaindb-driver.amd.js',
library: 'bigchaindb-driver',
libraryTarget: 'amd',
path: PATHS.BUNDLE,
}
]
/** PLUGINS **/
const PLUGINS = [
new webpack.NoEmitOnErrorsPlugin(),
]
const PROD_PLUGINS = [
/*
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
sourceMap: true,
}),
new webpack.LoaderOptionsPlugin({
debug: false,
minimize: true,
}),
*/
]
const OVERRIDES = {
// optimization: {
// minimize: false
// }
}
if (PRODUCTION) {
PLUGINS.push(...PROD_PLUGINS)
module.exports = outputs(common, 'production', OUTPUT_MAPPING, OVERRIDES)
} else {
module.exports = outputs(common, 'development', OUTPUT_MAPPING, OVERRIDES)
}
const configBoilerplate = {
entry: [PATHS.ENTRY],
devtool: PRODUCTION ? '#source-map' : '#inline-source-map',
resolve: {
extensions: ['.js'],
modules: ['node_modules'], // Don't use absolute path here to allow recursive matching
},
plugins: PLUGINS,
module: {
rules: [
{
test: /\.js$/,
exclude: [PATHS.NODE_MODULES],
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
}],
},
],
},
}
/** EXPORTED WEBPACK CONFIG **/
const config = OUTPUTS.map(output => {
const configCopy = Object.assign({}, configBoilerplate)
configCopy.output = output
return configCopy
})
module.exports = config

32
webpack.development.js Normal file
View File

@ -0,0 +1,32 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand, import/no-extraneous-dependencies */
'use strict'
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
devtool: 'inline-source-map',
optimization: {
minimizer: [
new TerserPlugin({
test: /vendor/,
}),
new TerserPlugin({
test: /^((?!(vendor)).)*.js$/,
})
],
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
}

59
webpack.parts.js Normal file
View File

@ -0,0 +1,59 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand, import/no-extraneous-dependencies */
'use strict'
const path = require('path')
const { merge } = require('webpack-merge')
const development = require('./webpack.development')
const production = require('./webpack.production')
const AddVendorsPlugin = require('./plugins/add-vendors-plugin')
const paths = {
entry: path.resolve(__dirname, './src/index.js'),
bundle: path.resolve(__dirname, 'dist/browser'),
}
const outputs = (base, env, mapping, overrides) => {
const collection = []
const library = 'bigchaindb-driver'
const windowLibrary = 'BigchainDB'
let environment = development
let ext = 'js'
if (env === 'production') {
environment = production
ext = `min.${ext}`
}
Object.entries(mapping).forEach(([target, extension]) => {
const filename = `[name].${library}.${extension}.${ext}`
const compiled = {
output: {
filename: filename,
library: target === 'window' ? windowLibrary : library,
libraryTarget: target,
path: paths.bundle
},
plugins: [
new AddVendorsPlugin(`${library}.${extension}.${ext}`)
]
}
collection.push(merge(base, environment, compiled, overrides))
})
return collection
}
module.exports = {
outputs,
paths
}

11
webpack.production.js Normal file
View File

@ -0,0 +1,11 @@
// Copyright BigchainDB GmbH and BigchainDB contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand */
'use strict'
module.exports = {
devtool: 'source-map',
}