Merge pull request #307 from bigchaindb/update-dependencies

Update dependencies
This commit is contained in:
getlarge 2021-03-10 09:21:13 +01:00 committed by GitHub
commit 7fe904061a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 606 additions and 407 deletions

View File

@ -1,12 +1,29 @@
{ {
"presets": [ "presets": [
"env" [
], "@babel/preset-env",
"plugins": [ {
"transform-export-extensions", "targets": [
"transform-object-assign", "> 0.25%, not dead",
"transform-object-rest-spread", "not IE 11",
["transform-runtime", { "polyfill": false, "regenerator": true }] "maintained node versions"
], ]
"sourceMaps": true }
} ]
],
"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,3 +1,6 @@
dist dist
node_modules node_modules
coverage 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'],
],
},
],
/**
* 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"
}

1
.husky/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_

View File

@ -10,9 +10,9 @@ services:
language: node_js language: node_js
node_js: node_js:
- 8
- 9
- 10 - 10
- 12
- 14
cache: cache:
directories: directories:
@ -20,7 +20,7 @@ cache:
env: env:
global: global:
- DOCKER_COMPOSE_VERSION=1.19.0 - DOCKER_COMPOSE_VERSION=1.28.5
before_install: before_install:
- .ci/travis-before-install.sh - .ci/travis-before-install.sh

227
API.md
View File

@ -1,9 +1,3 @@
<!---
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
--->
<!-- Generated by documentation.js. Update this documentation by updating the source code. --> <!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### Table of Contents ### Table of Contents
@ -23,36 +17,36 @@ Code is Apache-2.0 and docs are CC-BY-4.0
- [Parameters][13] - [Parameters][13]
- [listTransactions][14] - [listTransactions][14]
- [Parameters][15] - [Parameters][15]
- [listVotes][16] - [postTransaction][16]
- [Parameters][17] - [Parameters][17]
- [postTransaction][18] - [postTransactionSync][18]
- [Parameters][19] - [Parameters][19]
- [postTransactionSync][20] - [postTransactionAsync][20]
- [Parameters][21] - [Parameters][21]
- [postTransactionAsync][22] - [postTransactionCommit][22]
- [Parameters][23] - [Parameters][23]
- [postTransactionCommit][24] - [searchAssets][24]
- [Parameters][25] - [Parameters][25]
- [searchAssets][26] - [searchMetadata][26]
- [Parameters][27] - [Parameters][27]
- [searchMetadata][28] - [Transaction][28]
- [Parameters][29] - [serializeTransactionIntoCanonicalString][29]
- [Transaction][30] - [Parameters][30]
- [serializeTransactionIntoCanonicalString][31] - [makeCreateTransaction][31]
- [Parameters][32] - [Parameters][32]
- [makeCreateTransaction][33] - [makeEd25519Condition][33]
- [Parameters][34] - [Parameters][34]
- [makeEd25519Condition][35] - [makeOutput][35]
- [Parameters][36] - [Parameters][36]
- [makeOutput][37] - [makeSha256Condition][37]
- [Parameters][38] - [Parameters][38]
- [makeSha256Condition][39] - [makeThresholdCondition][39]
- [Parameters][40] - [Parameters][40]
- [makeThresholdCondition][41] - [makeTransferTransaction][41]
- [Parameters][42] - [Parameters][42]
- [makeTransferTransaction][43] - [signTransaction][43]
- [Parameters][44] - [Parameters][44]
- [signTransaction][45] - [delegateSignTransaction][45]
- [Parameters][46] - [Parameters][46]
- [ccJsonLoad][47] - [ccJsonLoad][47]
- [Parameters][48] - [Parameters][48]
@ -61,7 +55,7 @@ Code is Apache-2.0 and docs are CC-BY-4.0
## Ed25519Keypair ## Ed25519Keypair
[src/Ed25519Keypair.js:12-17][51] [src/Ed25519Keypair.js:16-21][51]
Type: [Object][52] Type: [Object][52]
@ -76,18 +70,17 @@ Type: [Object][52]
## Connection ## Connection
[src/connection.js:8-178][55] [src/connection.js:21-201][55]
Base connection
### Parameters ### Parameters
- `path` - `nodes`
- `headers` (optional, default `{}`) - `headers` **[Object][52]** Common headers for every request (optional, default `{}`)
- `timeout` **float** Optional timeout in secs (optional, default `DEFAULT_TIMEOUT`)
### getBlock ### getBlock
[src/connection.js:45-51][56] [src/connection.js:79-85][56]
#### Parameters #### Parameters
@ -95,7 +88,7 @@ Base connection
### getTransaction ### getTransaction
[src/connection.js:56-62][57] [src/connection.js:90-96][57]
#### Parameters #### Parameters
@ -103,7 +96,7 @@ Base connection
### listBlocks ### listBlocks
[src/connection.js:68-74][58] [src/connection.js:102-108][58]
#### Parameters #### Parameters
@ -112,7 +105,7 @@ Base connection
### listOutputs ### listOutputs
[src/connection.js:80-92][59] [src/connection.js:114-126][59]
#### Parameters #### Parameters
@ -121,24 +114,16 @@ Base connection
### listTransactions ### listTransactions
[src/connection.js:98-105][60] [src/connection.js:132-139][60]
#### Parameters #### Parameters
- `assetId` - `assetId`
- `operation` - `operation`
### listVotes
[src/connection.js:110-116][61]
#### Parameters
- `blockId`
### postTransaction ### postTransaction
[src/connection.js:121-123][62] [src/connection.js:144-146][61]
#### Parameters #### Parameters
@ -146,7 +131,7 @@ Base connection
### postTransactionSync ### postTransactionSync
[src/connection.js:128-133][63] [src/connection.js:151-156][62]
#### Parameters #### Parameters
@ -154,7 +139,7 @@ Base connection
### postTransactionAsync ### postTransactionAsync
[src/connection.js:139-144][64] [src/connection.js:162-167][63]
#### Parameters #### Parameters
@ -162,7 +147,7 @@ Base connection
### postTransactionCommit ### postTransactionCommit
[src/connection.js:150-155][65] [src/connection.js:173-178][64]
#### Parameters #### Parameters
@ -170,7 +155,7 @@ Base connection
### searchAssets ### searchAssets
[src/connection.js:160-166][66] [src/connection.js:183-189][65]
#### Parameters #### Parameters
@ -178,7 +163,7 @@ Base connection
### searchMetadata ### searchMetadata
[src/connection.js:171-177][67] [src/connection.js:194-200][66]
#### Parameters #### Parameters
@ -186,13 +171,13 @@ Base connection
## Transaction ## Transaction
[src/transaction.js:12-254][68] [src/transaction.js:16-280][67]
Construct Transactions Construct Transactions
### serializeTransactionIntoCanonicalString ### serializeTransactionIntoCanonicalString
[src/transaction.js:18-25][69] [src/transaction.js:22-29][68]
Canonically serializes a transaction into a string by sorting the keys Canonically serializes a transaction into a string by sorting the keys
@ -205,7 +190,7 @@ Returns **[string][54]** a canonically serialized Transaction
### makeCreateTransaction ### makeCreateTransaction
[src/transaction.js:76-83][70] [src/transaction.js:80-87][69]
Generate a `CREATE` transaction holding the `asset`, `metadata`, and `outputs`, to be signed by Generate a `CREATE` transaction holding the `asset`, `metadata`, and `outputs`, to be signed by
the `issuers`. the `issuers`.
@ -214,12 +199,12 @@ the `issuers`.
- `asset` **[Object][52]** Created asset's data - `asset` **[Object][52]** Created asset's data
- `metadata` **[Object][52]** Metadata for the Transaction - `metadata` **[Object][52]** Metadata for the Transaction
- `outputs` **[Array][71]&lt;[Object][52]>** Array of Output objects to add to the Transaction. - `outputs` **[Array][70]&lt;[Object][52]>** Array of Output objects to add to the Transaction.
Think of these as the recipients of the asset after 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 For `CREATE` Transactions, this should usually just be a list of
Outputs wrapping Ed25519 Conditions generated from the issuers' public Outputs wrapping Ed25519 Conditions generated from the issuers' public
keys (so that the issuers are the recipients of the created asset). keys (so that the issuers are the recipients of the created asset).
- `issuers` **...[Array][71]&lt;[string][54]>** Public key of one or more issuers to the asset being created by this - `issuers` **...[Array][70]&lt;[string][54]>** Public key of one or more issuers to the asset being created by this
Transaction. Transaction.
Note: Each of the private keys corresponding to the given public Note: Each of the private keys corresponding to the given public
keys MUST be used later (and in the same order) when signing the keys MUST be used later (and in the same order) when signing the
@ -230,7 +215,7 @@ Returns **[Object][52]** Unsigned transaction -- make sure to call signTransacti
### makeEd25519Condition ### makeEd25519Condition
[src/transaction.js:92-103][72] [src/transaction.js:96-107][71]
Create an Ed25519 Cryptocondition from an Ed25519 public key Create an Ed25519 Cryptocondition from an Ed25519 public key
to put into an Output of a Transaction to put into an Output of a Transaction
@ -238,13 +223,13 @@ to put into an Output of a Transaction
#### Parameters #### Parameters
- `publicKey` **[string][54]** base58 encoded Ed25519 public key for the recipient of the Transaction - `publicKey` **[string][54]** base58 encoded Ed25519 public key for the recipient of the Transaction
- `json` **[boolean][73]** If true returns a json object otherwise a crypto-condition type (optional, default `true`) - `json` **[boolean][72]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][52]** Ed25519 Condition (that will need to wrapped in an Output) Returns **[Object][52]** Ed25519 Condition (that will need to wrapped in an Output)
### makeOutput ### makeOutput
[src/transaction.js:113-133][74] [src/transaction.js:117-137][73]
Create an Output from a Condition. Create an Output from a Condition.
Note: Assumes the given Condition was generated from a Note: Assumes the given Condition was generated from a
@ -259,34 +244,34 @@ Returns **[Object][52]** An Output usable in a Transaction
### makeSha256Condition ### makeSha256Condition
[src/transaction.js:141-149][75] [src/transaction.js:145-153][74]
Create a Preimage-Sha256 Cryptocondition from a secret to put into an Output of a Transaction Create a Preimage-Sha256 Cryptocondition from a secret to put into an Output of a Transaction
#### Parameters #### Parameters
- `preimage` **[string][54]** Preimage to be hashed and wrapped in a crypto-condition - `preimage` **[string][54]** Preimage to be hashed and wrapped in a crypto-condition
- `json` **[boolean][73]** If true returns a json object otherwise a crypto-condition type (optional, default `true`) - `json` **[boolean][72]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][52]** Preimage-Sha256 Condition (that will need to wrapped in an Output) Returns **[Object][52]** Preimage-Sha256 Condition (that will need to wrapped in an Output)
### makeThresholdCondition ### makeThresholdCondition
[src/transaction.js:158-172][76] [src/transaction.js:162-176][75]
Create an Sha256 Threshold Cryptocondition from threshold to put into an Output of a Transaction Create an Sha256 Threshold Cryptocondition from threshold to put into an Output of a Transaction
#### Parameters #### Parameters
- `threshold` **[number][77]** - `threshold` **[number][76]**
- `subconditions` **[Array][71]** (optional, default `[]`) - `subconditions` **[Array][70]** (optional, default `[]`)
- `json` **[boolean][73]** If true returns a json object otherwise a crypto-condition type (optional, default `true`) - `json` **[boolean][72]** If true returns a json object otherwise a crypto-condition type (optional, default `true`)
Returns **[Object][52]** Sha256 Threshold Condition (that will need to wrapped in an Output) Returns **[Object][52]** Sha256 Threshold Condition (that will need to wrapped in an Output)
### makeTransferTransaction ### makeTransferTransaction
[src/transaction.js:195-216][78] [src/transaction.js:199-220][77]
Generate a `TRANSFER` transaction holding the `asset`, `metadata`, and `outputs`, that fulfills Generate a `TRANSFER` transaction holding the `asset`, `metadata`, and `outputs`, that fulfills
the `fulfilledOutputs` of `unspentTransaction`. the `fulfilledOutputs` of `unspentTransaction`.
@ -294,7 +279,7 @@ the `fulfilledOutputs` of `unspentTransaction`.
#### Parameters #### Parameters
- `unspentOutputs` - `unspentOutputs`
- `outputs` **[Array][71]&lt;[Object][52]>** Array of Output objects to add to the Transaction. - `outputs` **[Array][70]&lt;[Object][52]>** Array of Output objects to add to the Transaction.
Think of these as the recipients of the asset after 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 For `TRANSFER` Transactions, this should usually just be a list of
Outputs wrapping Ed25519 Conditions generated from the public keys of Outputs wrapping Ed25519 Conditions generated from the public keys of
@ -302,7 +287,7 @@ the `fulfilledOutputs` of `unspentTransaction`.
- `metadata` **[Object][52]** Metadata for the Transaction - `metadata` **[Object][52]** Metadata for the Transaction
- `unspentTransaction` **[Object][52]** Previous Transaction you have control over (i.e. can fulfill - `unspentTransaction` **[Object][52]** Previous Transaction you have control over (i.e. can fulfill
its Output Condition) its Output Condition)
- `OutputIndices` **...[number][77]** Indices of the Outputs in `unspentTransaction` that this - `OutputIndices` **...[number][76]** Indices of the Outputs in `unspentTransaction` that this
Transaction fulfills. Transaction fulfills.
Note that listed public keys listed must be used (and in Note that listed public keys listed must be used (and in
the same order) to sign the Transaction the same order) to sign the Transaction
@ -313,7 +298,7 @@ Returns **[Object][52]** Unsigned transaction -- make sure to call signTransacti
### signTransaction ### signTransaction
[src/transaction.js:229-253][79] [src/transaction.js:233-257][78]
Sign the given `transaction` with the given `privateKey`s, returning a new copy of `transaction` Sign the given `transaction` with the given `privateKey`s, returning a new copy of `transaction`
that's been signed. that's been signed.
@ -329,9 +314,23 @@ an exercise for the user.
Returns **[Object][52]** The signed version of `transaction`. Returns **[Object][52]** The signed version of `transaction`.
### delegateSignTransaction
[src/transaction.js:266-279][79]
Delegate signing of the given `transaction` returning a new copy of `transaction`
that's been signed.
#### Parameters
- `transaction` **[Object][52]** Transaction to sign. `transaction` is not modified.
- `signFn` **[Function][80]** Function signing the transaction, expected to return the fulfillment.
Returns **[Object][52]** The signed version of `transaction`.
## ccJsonLoad ## ccJsonLoad
[src/utils/ccJsonLoad.js:10-40][80] [src/utils/ccJsonLoad.js:14-44][81]
Loads a crypto-condition class (Fulfillment or Condition) from a BigchainDB JSON object Loads a crypto-condition class (Fulfillment or Condition) from a BigchainDB JSON object
@ -343,7 +342,7 @@ Returns **cc.Condition** Ed25519 Condition (that will need to wrapped in an Outp
## ccJsonify ## ccJsonify
[src/utils/ccJsonify.js:8-61][81] [src/utils/ccJsonify.js:12-65][82]
Serializes a crypto-condition class (Condition or Fulfillment) into a BigchainDB-compatible JSON Serializes a crypto-condition class (Condition or Fulfillment) into a BigchainDB-compatible JSON
@ -383,65 +382,65 @@ Returns **[Object][52]** Ed25519 Condition (that will need to wrapped in an Outp
[15]: #parameters-6 [15]: #parameters-6
[16]: #listvotes [16]: #posttransaction
[17]: #parameters-7 [17]: #parameters-7
[18]: #posttransaction [18]: #posttransactionsync
[19]: #parameters-8 [19]: #parameters-8
[20]: #posttransactionsync [20]: #posttransactionasync
[21]: #parameters-9 [21]: #parameters-9
[22]: #posttransactionasync [22]: #posttransactioncommit
[23]: #parameters-10 [23]: #parameters-10
[24]: #posttransactioncommit [24]: #searchassets
[25]: #parameters-11 [25]: #parameters-11
[26]: #searchassets [26]: #searchmetadata
[27]: #parameters-12 [27]: #parameters-12
[28]: #searchmetadata [28]: #transaction
[29]: #parameters-13 [29]: #serializetransactionintocanonicalstring
[30]: #transaction [30]: #parameters-13
[31]: #serializetransactionintocanonicalstring [31]: #makecreatetransaction
[32]: #parameters-14 [32]: #parameters-14
[33]: #makecreatetransaction [33]: #makeed25519condition
[34]: #parameters-15 [34]: #parameters-15
[35]: #makeed25519condition [35]: #makeoutput
[36]: #parameters-16 [36]: #parameters-16
[37]: #makeoutput [37]: #makesha256condition
[38]: #parameters-17 [38]: #parameters-17
[39]: #makesha256condition [39]: #makethresholdcondition
[40]: #parameters-18 [40]: #parameters-18
[41]: #makethresholdcondition [41]: #maketransfertransaction
[42]: #parameters-19 [42]: #parameters-19
[43]: #maketransfertransaction [43]: #signtransaction
[44]: #parameters-20 [44]: #parameters-20
[45]: #signtransaction [45]: #delegatesigntransaction
[46]: #parameters-21 [46]: #parameters-21
@ -453,7 +452,7 @@ Returns **[Object][52]** Ed25519 Condition (that will need to wrapped in an Outp
[50]: #parameters-23 [50]: #parameters-23
[51]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/Ed25519Keypair.js#L12-L17 "Source code on GitHub" [51]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/Ed25519Keypair.js#L16-L21 "Source code on GitHub"
[52]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [52]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
@ -461,56 +460,58 @@ Returns **[Object][52]** Ed25519 Condition (that will need to wrapped in an Outp
[54]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [54]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[55]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L8-L178 "Source code on GitHub" [55]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L21-L201 "Source code on GitHub"
[56]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L45-L51 "Source code on GitHub" [56]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L79-L85 "Source code on GitHub"
[57]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L56-L62 "Source code on GitHub" [57]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L90-L96 "Source code on GitHub"
[58]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L68-L74 "Source code on GitHub" [58]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L102-L108 "Source code on GitHub"
[59]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L80-L92 "Source code on GitHub" [59]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L114-L126 "Source code on GitHub"
[60]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L98-L105 "Source code on GitHub" [60]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L132-L139 "Source code on GitHub"
[61]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L110-L116 "Source code on GitHub" [61]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L144-L146 "Source code on GitHub"
[62]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L121-L123 "Source code on GitHub" [62]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L151-L156 "Source code on GitHub"
[63]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L128-L133 "Source code on GitHub" [63]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L162-L167 "Source code on GitHub"
[64]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L139-L144 "Source code on GitHub" [64]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L173-L178 "Source code on GitHub"
[65]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L150-L155 "Source code on GitHub" [65]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L183-L189 "Source code on GitHub"
[66]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L160-L166 "Source code on GitHub" [66]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/connection.js#L194-L200 "Source code on GitHub"
[67]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/connection.js#L171-L177 "Source code on GitHub" [67]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L16-L280 "Source code on GitHub"
[68]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L12-L254 "Source code on GitHub" [68]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L22-L29 "Source code on GitHub"
[69]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L18-L25 "Source code on GitHub" [69]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L80-L87 "Source code on GitHub"
[70]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L76-L83 "Source code on GitHub" [70]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[71]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [71]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L96-L107 "Source code on GitHub"
[72]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L92-L103 "Source code on GitHub" [72]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[73]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [73]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L117-L137 "Source code on GitHub"
[74]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L113-L133 "Source code on GitHub" [74]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L145-L153 "Source code on GitHub"
[75]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L141-L149 "Source code on GitHub" [75]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L162-L176 "Source code on GitHub"
[76]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L158-L172 "Source code on GitHub" [76]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[77]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [77]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L199-L220 "Source code on GitHub"
[78]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L195-L216 "Source code on GitHub" [78]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L233-L257 "Source code on GitHub"
[79]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/transaction.js#L229-L253 "Source code on GitHub" [79]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/transaction.js#L266-L279 "Source code on GitHub"
[80]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/utils/ccJsonLoad.js#L10-L40 "Source code on GitHub" [80]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[81]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/6a637f33e21a9f43503ec51f923bfdad60c57458/src/utils/ccJsonify.js#L8-L61 "Source code on GitHub" [81]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/utils/ccJsonLoad.js#L14-L44 "Source code on GitHub"
[82]: https://github.com/bigchaindb/js-bigchaindb-driver/blob/3c76d3bb21e8cac17c3ca69cb9bf31b7fbc115ae/src/utils/ccJsonify.js#L12-L65 "Source code on GitHub"

View File

@ -63,6 +63,7 @@ import driver from 'bigchaindb-driver'
```js ```js
const driver = require('bigchaindb-driver') const driver = require('bigchaindb-driver')
const base58 = require('bs58'); const base58 = require('bs58');
const crypto = require('crypto');
const { Ed25519Sha256 } = require('crypto-conditions'); const { Ed25519Sha256 } = require('crypto-conditions');
// BigchainDB server instance (e.g. https://example.com/api/v1/) // BigchainDB server instance (e.g. https://example.com/api/v1/)
@ -95,12 +96,13 @@ const txSigned = driver.Transaction.signTransaction(tx, alice.privateKey)
function signTransaction() { function signTransaction() {
// get privateKey from somewhere // get privateKey from somewhere
const privateKeyBuffer = Buffer.from(base58.decode(alice.privateKey)) const privateKeyBuffer = Buffer.from(base58.decode(alice.privateKey))
return function sign(transaction, input, transactionHash) { 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(); const ed25519Fulfillment = new Ed25519Sha256();
ed25519Fulfillment.sign( ed25519Fulfillment.sign(transactionHash, privateKeyBuffer);
Buffer.from(transactionHash, 'hex'),
privateKeyBuffer
);
return ed25519Fulfillment.serializeUri(); return ed25519Fulfillment.serializeUri();
}; };
} }

View File

@ -34,7 +34,7 @@ We follow [BEP-1](https://github.com/bigchaindb/BEPs/tree/master/1), which is ou
If that fails, then get it working. 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. 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 haver permission to do so). 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` `npm login`

View File

@ -1,4 +1,16 @@
{ {
"presets": ["es2015", "stage-3"], "presets": [["@babel/preset-env"]],
"plugins": ["syntax-async-functions", "transform-runtime", "transform-regenerator", "transform-async-to-generator"] "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

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

View File

@ -7,9 +7,8 @@
const driver = require('bigchaindb-driver') const driver = require('bigchaindb-driver')
require('dotenv').config() require('dotenv').config()
// ======== Preparation ======== // // ======== Preparation ======== //
const conn = new driver.Connection('https://example.com/api/v1/', { const conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
header1: 'header1_value', header1: 'header1_value',
header2: 'header2_value' header2: 'header2_value'
}) })
@ -26,11 +25,9 @@ const assetdata = {
const metadata = { 'planet': 'earth' } const metadata = { 'planet': 'earth' }
// Call async basic usage function // Call async basic usage function
basicUsage() basicUsage()
async function basicUsage() { async function basicUsage() {
// ======== Create Transaction Bicycle ======== // // ======== Create Transaction Bicycle ======== //
const txCreateAliceSimple = driver.Transaction.makeCreateTransaction( const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
@ -45,7 +42,6 @@ async function basicUsage() {
const txCreateAliceSimpleSigned = const txCreateAliceSimpleSigned =
driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey) driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey)
// ======== POST CREATE Transaction ======== // // ======== POST CREATE Transaction ======== //
const createdTx = await conn.postTransactionCommit(txCreateAliceSimpleSigned) const createdTx = await conn.postTransactionCommit(txCreateAliceSimpleSigned)
@ -60,7 +56,6 @@ async function basicUsage() {
await conn.postTransactionCommit(txTransferBobSigned) await conn.postTransactionCommit(txTransferBobSigned)
// ======== Querying Assets ======== // // ======== Querying Assets ======== //
const assets = await conn.searchAssets('Bicycle Inc.') const assets = await conn.searchAssets('Bicycle Inc.')
console.log(assets) // eslint-disable-line no-console console.log(assets) // eslint-disable-line no-console

View File

@ -7,9 +7,8 @@
const driver = require('bigchaindb-driver') const driver = require('bigchaindb-driver')
require('dotenv').config() require('dotenv').config()
// ======== Preparation ======== // // ======== Preparation ======== //
const conn = new driver.Connection('https://example.com/api/v1/', { const conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
header1: 'header1_value', header1: 'header1_value',
header2: 'header2_value' header2: 'header2_value'
}) })
@ -26,7 +25,6 @@ const assetdata = {
const metadata = { 'planet': 'earth' } const metadata = { 'planet': 'earth' }
// ======== Create Transaction Bicycle ======== // // ======== Create Transaction Bicycle ======== //
const txCreateAliceSimple = driver.Transaction.makeCreateTransaction( const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
assetdata, assetdata,
@ -60,7 +58,6 @@ conn.postTransactionCommit(txCreateAliceSimpleSigned)
console.log('Was Alice the previous owner?', tx.inputs[0].owners_before[0] === alice.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 ======== // // ======== Search Asset by Serial Number ======== //
.then(() => conn.searchAssets('Bicycle Inc.')) .then(() => conn.searchAssets('Bicycle Inc.'))
.then(assets => console.log('Found assets with serial number Bicycle Inc.:', assets)) // eslint-disable-line no-console .then(assets => console.log('Found assets with serial number Bicycle Inc.:', assets)) // eslint-disable-line no-console

View File

@ -7,7 +7,6 @@
const driver = require('bigchaindb-driver') const driver = require('bigchaindb-driver')
require('dotenv').config() require('dotenv').config()
// ======== Preparation ======== // // ======== Preparation ======== //
const conn = new driver.Connection('https://example.com/api/v1/', { const conn = new driver.Connection('https://example.com/api/v1/', {
header1: 'header1_value', header1: 'header1_value',
@ -16,7 +15,6 @@ const conn = new driver.Connection('https://example.com/api/v1/', {
const alice = new driver.Ed25519Keypair() const alice = new driver.Ed25519Keypair()
// ======== Asset Array ======== // // ======== Asset Array ======== //
const assetArray = [] const assetArray = []
assetArray.push({ 'bicycle': { 'serial_number': 'abc', 'manufacturer': 'BicyclesInc' } }) assetArray.push({ 'bicycle': { 'serial_number': 'abc', 'manufacturer': 'BicyclesInc' } })
@ -25,7 +23,6 @@ assetArray.push({ 'bicycle': { 'serial_number': 'fgh', 'manufacturer': 'Bicycles
const metadata = { 'planet': 'Pluto' } const metadata = { 'planet': 'Pluto' }
// ======== Create Transactions for bicycles ======== // // ======== Create Transactions for bicycles ======== //
function createTx(assetdata) { function createTx(assetdata) {
const txCreate = driver.Transaction.makeCreateTransaction( const txCreate = driver.Transaction.makeCreateTransaction(
@ -41,16 +38,13 @@ function createTx(assetdata) {
return conn.postTransactionCommit(txCreateSigned) return conn.postTransactionCommit(txCreateSigned)
} }
// ======== Execute all promises in order to post transactions and fetch them ======== // // ======== Execute all promises in order to post transactions and fetch them ======== //
Promise.all(assetArray.map(createTx)) Promise.all(assetArray.map(createTx))
// ======== Querying Assets for Assetdata ======== // // ======== Querying Assets for Assetdata ======== //
.then(() => conn.searchAssets('BicyclesInc')) .then(() => conn.searchAssets('BicyclesInc'))
.then(assets => console.log('Found assets with serial number "BicyclesInc":', assets)) // eslint-disable-line no-console .then(assets => console.log('Found assets with serial number "BicyclesInc":', assets)) // eslint-disable-line no-console
// ======== Querying Assets for Metadata ======== // // ======== Querying Assets for Metadata ======== //
.then(() => conn.searchMetadata('Pluto')) .then(() => conn.searchMetadata('Pluto'))
.then(assets => console.log('Found assets with metadata "Pluto":', assets)) // eslint-disable-line no-console .then(assets => console.log('Found assets with metadata "Pluto":', assets)) // eslint-disable-line no-console

View File

@ -10,82 +10,81 @@
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"author": "BigchainDB", "author": "BigchainDB",
"files": [
"dist"
],
"main": "./dist/node/index.js", "main": "./dist/node/index.js",
"browser": "./dist/browser/bigchaindb-driver.cjs2.min.js", "browser": "./dist/browser/bigchaindb-driver.cjs2.min.js",
"sideEffects": false, "sideEffects": false,
"scripts": { "scripts": {
"lint": "eslint ./{src,test,examples}/**/*.js", "lint": "eslint .",
"build": "npm run clean && npm run build:cjs && npm run build:dist", "build": "npm run clean && npm run build:cjs && npm run build:dist",
"build:bundle": "webpack", "build:bundle": "webpack",
"build:cjs": "cross-env BABEL_ENV=cjs babel ./src -d dist/node", "build:cjs": "cross-env BABEL_ENV=cjs babel ./src -d dist/node",
"build:dist": "cross-env NODE_ENV=production webpack", "build:dist": "cross-env NODE_ENV=production webpack",
"dev": "webpack -w", "dev": "webpack -w",
"clean": "rimraf dist/bundle dist/node", "clean": "rimraf dist/bundle dist/browser dist/node",
"test": "npm run lint && nyc ava test/ && npm run thanks && npm run report-coverage", "test": "npm run lint && nyc ava && npm run report-coverage",
"thanks": "cowsay Hi, thanks for your interest in BigchainDB. We appreciate your contribution!", "thanks": "cowsay Hi, thanks for your interest in BigchainDB. We appreciate your contribution!",
"release": "./node_modules/release-it/bin/release-it.js --git.tagName='v${version}' --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": "./node_modules/release-it/bin/release-it.js minor --git.tagName='v${version}' --github.release --npm.publish --non-interactive", "release-minor": "release-it minor --non-interactive",
"release-major": "./node_modules/release-it/bin/release-it.js major --git.tagName='v${version}' --github.release --npm.publish --non-interactive", "release-major": "release-it major --non-interactive",
"prepublishOnly": "npm run build", "prepublishOnly": "npm run build",
"report-coverage": "nyc report --reporter=lcov > coverage.lcov && codecov", "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" "doc": "documentation build src/index.js -f md -o API.md -g --markdown-toc"
},
"lint-staged": {
"*.js": [
"eslint"
]
}, },
"devDependencies": { "devDependencies": {
"ava": "^0.25.0", "@ava/babel": "^1.0.1",
"babel-cli": "^6.26.0", "@babel/cli": "^7.13.0",
"babel-core": "^6.26.3", "@babel/core": "^7.13.8",
"babel-eslint": "^9.0.0", "@babel/eslint-parser": "^7.13.8",
"babel-loader": "^7.1.5", "@babel/plugin-proposal-export-default-from": "^7.12.13",
"babel-plugin-add-module-exports": "^0.3.1", "@babel/plugin-proposal-object-rest-spread": "^7.13.8",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", "@babel/plugin-syntax-async-generators": "^7.8.4",
"babel-plugin-transform-export-extensions": "^6.22.0", "@babel/plugin-transform-async-to-generator": "^7.13.0",
"babel-plugin-transform-object-assign": "^6.22.0", "@babel/plugin-transform-object-assign": "^7.12.13",
"babel-plugin-transform-object-rest-spread": "^6.26.0", "@babel/plugin-transform-regenerator": "^7.12.13",
"babel-plugin-transform-runtime": "^6.23.0", "@babel/plugin-transform-runtime": "^7.13.9",
"babel-preset-env": "^1.7.0", "@babel/preset-env": "^7.13.9",
"babel-preset-es2015-no-commonjs": "0.0.2", "@babel/register": "^7.13.8",
"babel-runtime": "^6.26.0", "ava": "^3.15.0",
"cross-env": "^5.2.0", "babel-loader": "^8.2.2",
"documentation": "^10.1.0", "codecov": "^3.8.1",
"eslint": "^5.16.0", "cross-env": "^7.0.3",
"eslint-config-ascribe": "^3.0.5", "documentation": "^13.1.1",
"eslint-plugin-import": "^2.13.0", "eslint": "^7.21.0",
"husky": "^2.1.0", "eslint-config-airbnb-base": "^14.2.1",
"lint-staged": "^8.0.0", "eslint-plugin-import": "^2.22.1",
"nyc": "^14.0.0", "husky": "^5.1.3",
"release-it": "^12.6.3", "lint-staged": "^10.5.4",
"rimraf": "^2.6.2", "nyc": "^15.1.0",
"release-it": "^14.4.1",
"rewire": "^4.0.1",
"rimraf": "^3.0.2",
"sinon": "^7.3.2", "sinon": "^7.3.2",
"webpack": "^4.28.4", "terser-webpack-plugin": "^4.2.3",
"webpack-cli": "^3.0.8", "webpack": "^4.46.0",
"webpack-concat-plugin": "^3.0.0" "webpack-cli": "^4.5.0",
"webpack-concat-plugin": "^3.0.0",
"webpack-merge": "^5.7.3",
"webpack-sources": "^2.2.0"
}, },
"dependencies": { "dependencies": {
"@babel/runtime-corejs3": "^7.13.9",
"browser-resolve": "^1.11.3", "browser-resolve": "^1.11.3",
"bs58": "^4.0.1", "bs58": "^4.0.1",
"buffer": "^5.1.0", "buffer": "^6.0.3",
"clone": "^2.1.1", "clone": "^2.1.2",
"core-js": "^2.6.5", "core-js": "^3.9.1",
"crypto-conditions": "^2.0.1", "crypto-conditions": "^2.1.1",
"decamelize": "^3.2.0", "decamelize": "^5.0.0",
"es6-promise": "^4.2.4", "es6-promise": "^4.2.8",
"fetch-ponyfill": "^6.0.1", "fetch-ponyfill": "^7.1.0",
"isomorphic-fetch": "^2.2.1",
"js-sha3": "^0.8.0", "js-sha3": "^0.8.0",
"js-utility-belt": "^1.5.0",
"json-stable-stringify": "^1.0.1", "json-stable-stringify": "^1.0.1",
"query-string": "^6.0.0", "query-string": "^6.14.1",
"rewire": "^4.0.1", "sprintf-js": "^1.1.2",
"sprintf-js": "^1.1.1", "tweetnacl": "^1.0.3"
"tweetnacl": "^1.0.0",
"uglifyjs-webpack-plugin": "^2.1.2",
"webpack-merge": "^4.1.3",
"webpack-sources": "^1.1.0"
}, },
"keywords": [ "keywords": [
"bigchaindb", "bigchaindb",
@ -94,9 +93,15 @@
"decentralized", "decentralized",
"dapp" "dapp"
], ],
"lint-staged": {
"*.js": [
"eslint"
]
},
"ava": { "ava": {
"files": [ "files": [
"test/*.js" "test/**/*.js",
"!test/constants.js"
], ],
"source": [ "source": [
"**/*.{js,jsx}", "**/*.{js,jsx}",
@ -108,13 +113,29 @@
"tap": true, "tap": true,
"powerAssert": false, "powerAssert": false,
"require": [ "require": [
"babel-register" "@babel/register"
], ],
"babel": "inherit" "babel": true
}, },
"husky": { "husky": {
"hooks": { "hooks": {
"pre-commit": "lint-staged" "pre-commit": "lint-staged"
} }
},
"release-it": {
"github": {
"release": true
},
"git": {
"tagName": "v${version}"
},
"hooks": {
"before:init": [
"npm run test"
]
},
"npm": {
"publish": true
}
} }
} }

View File

@ -2,6 +2,8 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are 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') const { ConcatSource } = require('webpack-sources')
module.exports = class AddVendorsPlugin { module.exports = class AddVendorsPlugin {
@ -18,9 +20,9 @@ module.exports = class AddVendorsPlugin {
const vendor = compilation.assets[`vendors.${this.base}`] const vendor = compilation.assets[`vendors.${this.base}`]
if (main && vendor) { if (main && vendor) {
const compiledAsset = new ConcatSource(main.children[0]) const compiledAsset = new ConcatSource(main._value[0])
compiledAsset.add(vendor) compiledAsset.add(vendor)
compiledAsset.add(main.children[1]) compiledAsset.add(main._value[1])
compilation.assets = {} compilation.assets = {}
compilation.assets[this.base] = compiledAsset compilation.assets[this.base] = compiledAsset
} else if (main && mainMap) { } else if (main && mainMap) {
@ -28,6 +30,7 @@ module.exports = class AddVendorsPlugin {
compilation.assets[this.base] = main compilation.assets[this.base] = main
compilation.assets[`${this.base}.map`] = mainMap compilation.assets[`${this.base}.map`] = mainMap
} }
callback() callback()
} }
) )

View File

@ -3,7 +3,7 @@
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
import base58 from 'bs58' import base58 from 'bs58'
import nacl from 'tweetnacl' import { sign } from 'tweetnacl'
/** /**
* @public * @public
@ -14,7 +14,7 @@ import nacl from 'tweetnacl'
* @property {string} privateKey * @property {string} privateKey
*/ */
export default function Ed25519Keypair(seed) { export default function Ed25519Keypair(seed) {
const keyPair = seed ? nacl.sign.keyPair.fromSeed(seed) : nacl.sign.keyPair() const keyPair = seed ? sign.keyPair.fromSeed(seed) : sign.keyPair()
this.publicKey = base58.encode(Buffer.from(keyPair.publicKey)) 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) // tweetnacl's generated secret key is the secret key + public key (resulting in a 64-byte buffer)
this.privateKey = base58.encode(Buffer.from(keyPair.secretKey.slice(0, 32))) this.privateKey = base58.encode(Buffer.from(keyPair.secretKey.slice(0, 32)))

View File

@ -2,19 +2,24 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
import { import { Promise } from 'es6-promise'
Promise
} from 'es6-promise'
import fetchPonyfill from 'fetch-ponyfill' import fetchPonyfill from 'fetch-ponyfill'
import { import { vsprintf } from 'sprintf-js'
vsprintf
} from 'sprintf-js'
import formatText from './format_text' import formatText from './format_text'
import stringifyAsQueryParam from './stringify_as_query_param' 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 * @private
@ -45,17 +50,15 @@ function handleResponse(res) {
// If status is not a 2xx (based on Response.ok), assume it's an error // 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 // See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
if (!(res && res.ok)) { if (!(res && res.ok)) {
const errorObject = { throw new ResponseError(
message: 'HTTP Error: Requested page not reachable', 'HTTP Error: Requested page not reachable',
status: `${res.status} ${res.statusText}`, `${res.status} ${res.statusText}`,
requestURI: res.url res.url
} )
throw errorObject
} }
return res return res
} }
/** /**
* @private * @private
* imported from https://github.com/bigchaindb/js-utility-belt/ * imported from https://github.com/bigchaindb/js-utility-belt/

View File

@ -22,7 +22,7 @@ export default class Connection {
// This driver implements the BEP-14 https://github.com/bigchaindb/BEPs/tree/master/14 // This driver implements the BEP-14 https://github.com/bigchaindb/BEPs/tree/master/14
constructor(nodes, headers = {}, timeout = DEFAULT_TIMEOUT) { constructor(nodes, headers = {}, timeout = DEFAULT_TIMEOUT) {
// Copy object // Copy object
this.headers = Object.assign({}, headers) this.headers = { ...headers }
// Validate headers // Validate headers
Object.keys(headers).forEach(header => { Object.keys(headers).forEach(header => {
@ -49,7 +49,7 @@ export default class Connection {
if (typeof node === 'string') { if (typeof node === 'string') {
return { 'endpoint': node, 'headers': headers } return { 'endpoint': node, 'headers': headers }
} else { } else {
const allHeaders = Object.assign({}, headers, node.headers) const allHeaders = { ...headers, ...node.headers }
return { 'endpoint': node.endpoint, 'headers': allHeaders } return { 'endpoint': node.endpoint, 'headers': allHeaders }
} }
} }
@ -155,7 +155,6 @@ export default class Connection {
}) })
} }
/** /**
* @param transaction * @param transaction
*/ */
@ -166,7 +165,6 @@ export default class Connection {
}) })
} }
/** /**
* @param transaction * @param transaction
*/ */

View File

@ -4,7 +4,6 @@
import { sprintf } from 'sprintf-js' import { sprintf } from 'sprintf-js'
// Regexes taken from or inspired by sprintf-js // Regexes taken from or inspired by sprintf-js
const Regex = { const Regex = {
TEMPLATE_LITERAL: /\${([^)]+?)}/g, TEMPLATE_LITERAL: /\${([^)]+?)}/g,

View File

@ -19,7 +19,6 @@ const ERROR_FROM_SERVER = 'HTTP Error: Requested page not reachable'
* default settings, and response handling. * default settings, and response handling.
*/ */
export default class Request { export default class Request {
constructor(node) { constructor(node) {
this.node = node this.node = node
@ -33,14 +32,15 @@ export default class Request {
return Promise.reject(new Error('Request was not given a url.')) return Promise.reject(new Error('Request was not given a url.'))
} }
// Load default fetch configuration and remove any falsy query parameters // Load default fetch configuration and remove any falsy query parameters
const requestConfig = Object.assign({}, this.node.headers, DEFAULT_REQUEST_CONFIG, config, { const requestConfig = {
...this.node.headers,
...DEFAULT_REQUEST_CONFIG,
...config,
query: config.query && sanitize(config.query) query: config.query && sanitize(config.query)
}) }
const apiUrl = this.node.endpoint + urlPath const apiUrl = this.node.endpoint + urlPath
if (requestConfig.jsonBody) { if (requestConfig.jsonBody) {
requestConfig.headers = Object.assign({}, requestConfig.headers, { requestConfig.headers = { ...requestConfig.headers, 'Content-Type': 'application/json' }
'Content-Type': 'application/json'
})
} }
// If connectionError occurs, a timestamp equal to now + // If connectionError occurs, a timestamp equal to now +

View File

@ -2,9 +2,8 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
import coreIncludes from 'core-js/library/fn/array/includes' import 'core-js/features/array/includes'
import coreObjectEntries from 'core-js/library/fn/object/entries' import 'core-js/features/object/entries'
/** /**
* @private * @private
@ -14,8 +13,8 @@ import coreObjectEntries from 'core-js/library/fn/object/entries'
*/ */
function filterFromObject(obj, filter, { isInclusion = true } = {}) { function filterFromObject(obj, filter, { isInclusion = true } = {}) {
if (filter && Array.isArray(filter)) { if (filter && Array.isArray(filter)) {
return applyFilterOnObject(obj, isInclusion ? (val => coreIncludes(filter, val)) return applyFilterOnObject(obj, isInclusion ? (val => filter.includes(val))
: (val => !coreIncludes(filter, val))) : (val => !filter.includes(val)))
} else if (filter && typeof filter === 'function') { } else if (filter && typeof filter === 'function') {
// Flip the filter fn's return if it's for inclusion // Flip the filter fn's return if it's for inclusion
return applyFilterOnObject(obj, isInclusion ? filter return applyFilterOnObject(obj, isInclusion ? filter
@ -32,11 +31,11 @@ function filterFromObject(obj, filter, { isInclusion = true } = {}) {
*/ */
function applyFilterOnObject(obj, filterFn) { function applyFilterOnObject(obj, filterFn) {
if (filterFn == null) { if (filterFn == null) {
return Object.assign({}, obj) return { ...obj }
} }
const filteredObj = {} const filteredObj = {}
coreObjectEntries(obj).forEach(([key, val]) => { Object.entries(obj).forEach(([key, val]) => {
if (filterFn(val, key)) { if (filterFn(val, key)) {
filteredObj[key] = val filteredObj[key] = val
} }

View File

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

View File

@ -94,7 +94,7 @@ export default class Transaction {
* @returns {Object} Ed25519 Condition (that will need to wrapped in an Output) * @returns {Object} Ed25519 Condition (that will need to wrapped in an Output)
*/ */
static makeEd25519Condition(publicKey, json = true) { static makeEd25519Condition(publicKey, json = true) {
const publicKeyBuffer = Buffer.from(base58.decode(publicKey)) const publicKeyBuffer = base58.decode(publicKey)
const ed25519Fulfillment = new cc.Ed25519Sha256() const ed25519Fulfillment = new cc.Ed25519Sha256()
ed25519Fulfillment.setPublicKey(publicKeyBuffer) ed25519Fulfillment.setPublicKey(publicKeyBuffer)
@ -144,7 +144,7 @@ export default class Transaction {
*/ */
static makeSha256Condition(preimage, json = true) { static makeSha256Condition(preimage, json = true) {
const sha256Fulfillment = new cc.PreimageSha256() const sha256Fulfillment = new cc.PreimageSha256()
sha256Fulfillment.preimage = Buffer.from(preimage) sha256Fulfillment.setPreimage(Buffer.from(preimage))
if (json) { if (json) {
return ccJsonify(sha256Fulfillment) return ccJsonify(sha256Fulfillment)
@ -161,11 +161,12 @@ export default class Transaction {
*/ */
static makeThresholdCondition(threshold, subconditions = [], json = true) { static makeThresholdCondition(threshold, subconditions = [], json = true) {
const thresholdCondition = new cc.ThresholdSha256() const thresholdCondition = new cc.ThresholdSha256()
thresholdCondition.threshold = threshold thresholdCondition.setThreshold(threshold)
subconditions.forEach((subcondition) => { subconditions.forEach((subcondition) => {
// TODO: add support for Condition and URIs // TODO: add support for Condition
thresholdCondition.addSubfulfillment(subcondition) thresholdCondition.addSubfulfillment(subcondition)
// ? Should be thresholdCondition.addSubcondition(subcondition)
}) })
if (json) { if (json) {
@ -237,7 +238,7 @@ export default class Transaction {
signedTx.inputs.forEach((input, index) => { signedTx.inputs.forEach((input, index) => {
const privateKey = privateKeys[index] const privateKey = privateKeys[index]
const privateKeyBuffer = Buffer.from(base58.decode(privateKey)) const privateKeyBuffer = base58.decode(privateKey)
const transactionUniqueFulfillment = input.fulfills ? serializedTransaction const transactionUniqueFulfillment = input.fulfills ? serializedTransaction
.concat(input.fulfills.transaction_id) .concat(input.fulfills.transaction_id)
@ -268,12 +269,8 @@ export default class Transaction {
const serializedTransaction = const serializedTransaction =
Transaction.serializeTransactionIntoCanonicalString(transaction) Transaction.serializeTransactionIntoCanonicalString(transaction)
signedTx.inputs.forEach((input) => { signedTx.inputs.forEach((input, index) => {
const transactionUniqueFulfillment = input.fulfills ? serializedTransaction const fulfillmentUri = signFn(serializedTransaction, input, index)
.concat(input.fulfills.transaction_id)
.concat(input.fulfills.output_index) : serializedTransaction
const transactionHash = sha256Hash(transactionUniqueFulfillment)
const fulfillmentUri = signFn(input, transactionHash)
input.fulfillment = fulfillmentUri input.fulfillment = fulfillmentUri
}) })

View File

@ -4,7 +4,6 @@
import Request from './request' import Request from './request'
/** /**
* *
* @private * @private
@ -13,7 +12,6 @@ import Request from './request'
* customizable in the future). * customizable in the future).
*/ */
export default class Transport { export default class Transport {
constructor(nodes, timeout) { constructor(nodes, timeout) {
this.connectionPool = [] this.connectionPool = []
@ -46,28 +44,21 @@ export default class Transport {
connection = this.pickConnection() connection = this.pickConnection()
// Date in milliseconds // Date in milliseconds
const startTime = Date.now() const startTime = Date.now()
try { // eslint-disable-next-line no-await-in-loop
// eslint-disable-next-line no-await-in-loop response = await connection.request(
response = await connection.request( path,
path, headers,
headers, this.timeout,
this.timeout, this.maxBackoffTime
this.maxBackoffTime )
) const elapsed = Date.now() - startTime
const elapsed = Date.now() - startTime if (connection.backoffTime > 0 && this.timeout > 0) {
if (connection.backoffTime > 0 && this.timeout > 0) { this.timeout -= elapsed
this.timeout -= elapsed } else {
} else { // No connection error, the response is valid
// No connection error, the response is valid return response
return response
}
} catch (err) {
throw err
} }
} }
const errorObject = { throw new Error('TimeoutError')
message: 'TimeoutError',
}
throw errorObject
} }
} }

View File

@ -20,14 +20,11 @@ test('HandleResponse does not throw error for response ok', t => {
}) })
test('baseRequest test query and vsprint', async t => { test('baseRequest test query and vsprint', async t => {
const target = { const error = await t.throwsAsync(baseRequest('https://%s.com/', {
message: 'HTTP Error: Requested page not reachable',
requestURI: 'https://www.google.com/teapot',
status: '418 I\'m a Teapot',
}
const error = await t.throws(baseRequest('https://%s.com/', {
urlTemplateSpec: ['google'], urlTemplateSpec: ['google'],
query: 'teapot' query: 'teapot'
})) }), { instanceOf: Error, message: 'HTTP Error: Requested page not reachable' })
t.deepEqual(target, error)
t.is(error.requestURI, 'https://www.google.com/teapot')
t.is(error.status, '418 I\'m a Teapot')
}) })

View File

@ -22,8 +22,13 @@ test('Payload thrown at incorrect API_PATH', async t => {
status: '404 NOT FOUND', status: '404 NOT FOUND',
requestURI: 'http://localhost:9984/api/wrong/transactions/transactionId' requestURI: 'http://localhost:9984/api/wrong/transactions/transactionId'
} }
const error = await t.throws(connection.getTransaction('transactionId')) const error = await t.throwsAsync(connection.getTransaction('transactionId'), {
t.deepEqual(target, error) 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 => { test('Generate API URLS', t => {
@ -100,7 +105,6 @@ test('Request with custom headers', t => {
t.truthy(testConn.transport.forwardRequest.calledWith(PATH, expectedOptions)) t.truthy(testConn.transport.forwardRequest.calledWith(PATH, expectedOptions))
}) })
test('Get block for a block id', t => { test('Get block for a block id', t => {
const expectedPath = 'path' const expectedPath = 'path'
const blockHeight = 'abc' const blockHeight = 'abc'
@ -115,7 +119,6 @@ test('Get block for a block id', t => {
)) ))
}) })
test('Get transaction for a transaction id', t => { test('Get transaction for a transaction id', t => {
const expectedPath = 'path' const expectedPath = 'path'
const transactionId = 'abc' const transactionId = 'abc'
@ -130,7 +133,6 @@ test('Get transaction for a transaction id', t => {
)) ))
}) })
test('Get list of blocks for a transaction id', t => { test('Get list of blocks for a transaction id', t => {
const expectedPath = 'path' const expectedPath = 'path'
const transactionId = 'abc' const transactionId = 'abc'
@ -149,7 +151,6 @@ test('Get list of blocks for a transaction id', t => {
)) ))
}) })
test('Get list of transactions for an asset id', t => { test('Get list of transactions for an asset id', t => {
const expectedPath = 'path' const expectedPath = 'path'
const assetId = 'abc' const assetId = 'abc'
@ -170,7 +171,6 @@ test('Get list of transactions for an asset id', t => {
)) ))
}) })
test('Get outputs for a public key and no spent flag', t => { test('Get outputs for a public key and no spent flag', t => {
const expectedPath = 'path' const expectedPath = 'path'
const publicKey = 'publicKey' const publicKey = 'publicKey'
@ -185,7 +185,6 @@ test('Get outputs for a public key and no spent flag', t => {
)) ))
}) })
test('Get outputs for a public key and spent=false', t => { test('Get outputs for a public key and spent=false', t => {
const expectedPath = 'path' const expectedPath = 'path'
const publicKey = 'publicKey' const publicKey = 'publicKey'
@ -201,7 +200,6 @@ test('Get outputs for a public key and spent=false', t => {
)) ))
}) })
test('Get outputs for a public key and spent=true', t => { test('Get outputs for a public key and spent=true', t => {
const expectedPath = 'path' const expectedPath = 'path'
const publicKey = 'publicKey' const publicKey = 'publicKey'
@ -217,7 +215,6 @@ test('Get outputs for a public key and spent=true', t => {
)) ))
}) })
test('Get asset for text', t => { test('Get asset for text', t => {
const expectedPath = 'path' const expectedPath = 'path'
const search = 'abc' const search = 'abc'
@ -232,7 +229,6 @@ test('Get asset for text', t => {
)) ))
}) })
test('Get metadata for text', t => { test('Get metadata for text', t => {
const expectedPath = 'path' const expectedPath = 'path'
const search = 'abc' const search = 'abc'

View File

@ -2,7 +2,7 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
import test from 'ava' import { createHash } from 'crypto'
import base58 from 'bs58' import base58 from 'bs58'
import { Ed25519Sha256 } from 'crypto-conditions' import { Ed25519Sha256 } from 'crypto-conditions'
import { Transaction, Ed25519Keypair } from '../src' import { Transaction, Ed25519Keypair } from '../src'
@ -34,20 +34,20 @@ export const bobCondition = Transaction.makeEd25519Condition(bob.publicKey)
export const bobOutput = Transaction.makeOutput(bobCondition) export const bobOutput = Transaction.makeOutput(bobCondition)
export function delegatedSignTransaction(...keyPairs) { export function delegatedSignTransaction(...keyPairs) {
return function sign(input, transactionHash) { return function sign(serializedTransaction, input) {
const filteredKeyPairs = keyPairs.filter(({ publicKey }) => const transactionUniqueFulfillment = input.fulfills ? serializedTransaction
input.owners_before.includes(publicKey)) .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)
)
const ed25519Fulfillment = new Ed25519Sha256() const ed25519Fulfillment = new Ed25519Sha256()
filteredKeyPairs.forEach(keyPair => { filteredKeyPairs.forEach(keyPair => {
const privateKey = Buffer.from(base58.decode(keyPair.privateKey)) const privateKey = Buffer.from(base58.decode(keyPair.privateKey))
ed25519Fulfillment.sign( ed25519Fulfillment.sign(transactionHash, privateKey)
Buffer.from(transactionHash, 'hex'),
privateKey
)
}) })
return ed25519Fulfillment.serializeUri() return ed25519Fulfillment.serializeUri()
} }
} }
// TODO: https://github.com/avajs/ava/issues/1190
test('', () => 'dirty hack. TODO: Exclude this file from being run by ava')

View File

@ -17,7 +17,6 @@ import {
delegatedSignTransaction delegatedSignTransaction
} from '../constants' } from '../constants'
test('Keypair is created', t => { test('Keypair is created', t => {
const keyPair = new Ed25519Keypair() const keyPair = new Ed25519Keypair()
@ -25,10 +24,6 @@ test('Keypair is created', t => {
t.truthy(keyPair.privateKey) t.truthy(keyPair.privateKey)
}) })
// TODO: The following tests are a bit messy currently, please do:
//
// - tidy up dependency on `pollStatusAndFetchTransaction`
test('Valid CREATE transaction with default node', t => { test('Valid CREATE transaction with default node', t => {
const conn = new Connection() const conn = new Connection()
@ -46,7 +41,6 @@ test('Valid CREATE transaction with default node', t => {
}) })
}) })
test('Valid CREATE transaction using async', t => { test('Valid CREATE transaction using async', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -62,7 +56,6 @@ test('Valid CREATE transaction using async', t => {
.then(resTx => t.truthy(resTx)) .then(resTx => t.truthy(resTx))
}) })
test('Valid CREATE transaction using sync', t => { test('Valid CREATE transaction using sync', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -78,7 +71,6 @@ test('Valid CREATE transaction using sync', t => {
.then(resTx => t.truthy(resTx)) .then(resTx => t.truthy(resTx))
}) })
test('Valid TRANSFER transaction with single Ed25519 input', t => { test('Valid TRANSFER transaction with single Ed25519 input', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
const createTx = Transaction.makeCreateTransaction( const createTx = Transaction.makeCreateTransaction(
@ -108,7 +100,6 @@ test('Valid TRANSFER transaction with single Ed25519 input', t => {
}) })
}) })
test('Valid TRANSFER transaction with multiple Ed25519 inputs', t => { test('Valid TRANSFER transaction with multiple Ed25519 inputs', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
const createTx = Transaction.makeCreateTransaction( const createTx = Transaction.makeCreateTransaction(
@ -139,7 +130,6 @@ test('Valid TRANSFER transaction with multiple Ed25519 inputs', t => {
}) })
}) })
test('Valid TRANSFER transaction with multiple Ed25519 inputs from different transactions', t => { test('Valid TRANSFER transaction with multiple Ed25519 inputs from different transactions', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair() const carol = new Ed25519Keypair()
@ -264,7 +254,6 @@ test('Search for spent and unspent outputs of a given public key', t => {
const trentCondition = Transaction.makeEd25519Condition(trent.publicKey) const trentCondition = Transaction.makeEd25519Condition(trent.publicKey)
const trentOutput = Transaction.makeOutput(trentCondition) const trentOutput = Transaction.makeOutput(trentCondition)
const createTx = Transaction.makeCreateTransaction( const createTx = Transaction.makeCreateTransaction(
asset(), asset(),
metaData, metaData,
@ -295,7 +284,6 @@ test('Search for spent and unspent outputs of a given public key', t => {
.then(outputs => t.truthy(outputs.length === 2)) .then(outputs => t.truthy(outputs.length === 2))
}) })
test('Search for unspent outputs for a given public key', t => { test('Search for unspent outputs for a given public key', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair() const carol = new Ed25519Keypair()
@ -335,7 +323,6 @@ test('Search for unspent outputs for a given public key', t => {
.then(outputs => t.truthy(outputs.length === 2)) .then(outputs => t.truthy(outputs.length === 2))
}) })
test('Search for spent outputs for a given public key', t => { test('Search for spent outputs for a given public key', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
const carol = new Ed25519Keypair() const carol = new Ed25519Keypair()
@ -375,7 +362,6 @@ test('Search for spent outputs for a given public key', t => {
.then(outputs => t.truthy(outputs.length === 1)) .then(outputs => t.truthy(outputs.length === 1))
}) })
test('Search for an asset', t => { test('Search for an asset', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -398,7 +384,6 @@ test('Search for an asset', t => {
)) ))
}) })
test('Search for metadata', t => { test('Search for metadata', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -421,7 +406,6 @@ test('Search for metadata', t => {
)) ))
}) })
test('Search blocks containing a transaction', t => { test('Search blocks containing a transaction', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -443,7 +427,6 @@ test('Search blocks containing a transaction', t => {
.then(transactions => t.truthy(transactions.length === 1)) .then(transactions => t.truthy(transactions.length === 1))
}) })
test('Search transaction containing an asset', t => { test('Search transaction containing an asset', t => {
const conn = new Connection(API_PATH) const conn = new Connection(API_PATH)
@ -465,7 +448,8 @@ test('Search transaction containing an asset', t => {
}) })
}) })
test('Content-Type cannot be set', 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

@ -5,7 +5,6 @@
import test from 'ava' import test from 'ava'
import Connection from '../../src/connection' import Connection from '../../src/connection'
const conn = new Connection() const conn = new Connection()
test('Ensure that BackoffTimedelta works properly', t => { test('Ensure that BackoffTimedelta works properly', t => {
@ -18,14 +17,10 @@ test('Ensure that BackoffTimedelta works properly', t => {
test('Ensure that updateBackoffTime throws and error on TimeoutError', async t => { test('Ensure that updateBackoffTime throws and error on TimeoutError', async t => {
const req = conn.transport.pickConnection() const req = conn.transport.pickConnection()
const target = { const errorMessage = 'TimeoutError'
message: 'TimeoutError' req.connectionError = new Error(errorMessage)
}
req.connectionError = target
const error = t.throws(() => { t.throws(() => {
req.updateBackoffTime() req.updateBackoffTime()
}) }, { instanceOf: Error, message: errorMessage })
t.deepEqual(target, error)
}) })

View File

@ -9,7 +9,6 @@ const sanitize = rewire('../../src/sanitize.js')
const applyFilterOnObject = sanitize.__get__('applyFilterOnObject') const applyFilterOnObject = sanitize.__get__('applyFilterOnObject')
const filterFromObject = sanitize.__get__('filterFromObject') const filterFromObject = sanitize.__get__('filterFromObject')
test('Ensure that null filter returns same object', t => { test('Ensure that null filter returns same object', t => {
const expected = { 'testObj': 'test' } const expected = { 'testObj': 'test' }
const actual = applyFilterOnObject({ 'testObj': 'test' }, null) const actual = applyFilterOnObject({ 'testObj': 'test' }, null)
@ -17,7 +16,6 @@ test('Ensure that null filter returns same object', t => {
t.deepEqual(actual, expected) t.deepEqual(actual, expected)
}) })
test('Ensure function filter with isInclusion true works properly', t => { test('Ensure function filter with isInclusion true works properly', t => {
const testObj = [true, false, undefined, '', 0, null] const testObj = [true, false, undefined, '', 0, null]
const expected = { 0: true } const expected = { 0: true }
@ -26,7 +24,6 @@ test('Ensure function filter with isInclusion true works properly', t => {
t.deepEqual(actual, expected) t.deepEqual(actual, expected)
}) })
test('Ensure function filter with isInclusion false works properly', t => { 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 testObj = [false, true, 1, 10, 'this will be removed as it is truthy']
const expected = { 0: false } const expected = { 0: false }
@ -35,7 +32,6 @@ test('Ensure function filter with isInclusion false works properly', t => {
t.deepEqual(actual, expected) t.deepEqual(actual, expected)
}) })
test('Ensure array filter with isInclusion true works properly', t => { test('Ensure array filter with isInclusion true works properly', t => {
const testObj = [true, false, undefined, '', 0, null] const testObj = [true, false, undefined, '', 0, null]
const expected = { 0: true } const expected = { 0: true }
@ -44,7 +40,6 @@ test('Ensure array filter with isInclusion true works properly', t => {
t.deepEqual(actual, expected) t.deepEqual(actual, expected)
}) })
test('Ensure array filter with isInclusion false works properly', t => { test('Ensure array filter with isInclusion false works properly', t => {
const testObj = [false, true, 1, 10] const testObj = [false, true, 1, 10]
const expected = { 0: false } const expected = { 0: false }
@ -53,12 +48,8 @@ test('Ensure array filter with isInclusion false works properly', t => {
t.deepEqual(actual, expected) t.deepEqual(actual, expected)
}) })
test('Ensure throws error when given invalid filter', t => { test('Ensure throws error when given invalid filter', t => {
const error = t.throws(() => { t.throws(() => {
filterFromObject({}, 'lol') filterFromObject({}, 'lol')
}, Error) }, { instanceOf: Error, message: 'The given filter is not an array or function. Filter aborted' })
t.is(error.message, 'The given filter is not an array or function. Filter aborted')
}) })

View File

@ -41,12 +41,10 @@ test('formatText test type 3', t => {
}) })
test('formatText test throws', t => { test('formatText test throws', t => {
const error = t.throws(() => { t.throws(() => {
formatText( formatText(
'This will give ${error.}', // eslint-disable-line no-template-curly-in-string 'This will give ${error.}', // eslint-disable-line no-template-curly-in-string
{ error: [{}] } { error: [{}] }
) )
}, SyntaxError) }, { instanceOf: SyntaxError, message: '[formatText] failed to parse named argument key: error.' })
t.is(error.message, '[formatText] failed to parse named argument key: error.')
}) })

View File

@ -34,7 +34,6 @@ test('Sha256Condition fulfillment', t => {
t.deepEqual(target, Transaction.makeSha256Condition(preimage)) t.deepEqual(target, Transaction.makeSha256Condition(preimage))
}) })
test('Threshold condition encoding', t => { test('Threshold condition encoding', t => {
const publicKey = '4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS' const publicKey = '4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS'
const ed25519 = Transaction.makeEd25519Condition(publicKey, false) const ed25519 = Transaction.makeEd25519Condition(publicKey, false)
@ -64,7 +63,6 @@ test('Threshold condition encoding', t => {
t.deepEqual(target, output) t.deepEqual(target, output)
}) })
test('Fulfillment correctly formed', t => { test('Fulfillment correctly formed', t => {
const alice = new Ed25519Keypair() const alice = new Ed25519Keypair()
const txCreate = Transaction.makeCreateTransaction( const txCreate = Transaction.makeCreateTransaction(
@ -115,23 +113,6 @@ test('Delegated signature is correct', t => {
t.deepEqual(signCreateTransaction, delegatedSignCreateTransaction) t.deepEqual(signCreateTransaction, delegatedSignCreateTransaction)
}) })
test('CryptoConditions JSON load', t => {
const cond = ccJsonLoad({
type: 'threshold-sha-256',
threshold: 1,
subconditions: [{
type: 'ed25519-sha-256',
public_key: 'a'
},
{
hash: 'a'
}],
})
t.truthy(cond.subconditions.length === 2)
})
test('CryptoConditions JSON load', t => { test('CryptoConditions JSON load', t => {
const cond = ccJsonLoad({ const cond = ccJsonLoad({
type: 'threshold-sha-256', type: 'threshold-sha-256',

View File

@ -15,7 +15,6 @@ import {
transferTx transferTx
} from '../constants' } from '../constants'
test('Create valid output with default amount', t => { test('Create valid output with default amount', t => {
const condition = { const condition = {
details: { details: {
@ -32,7 +31,6 @@ test('Create valid output with default amount', t => {
t.deepEqual(res, expected) t.deepEqual(res, expected)
}) })
test('Create valid output with custom amount', t => { test('Create valid output with custom amount', t => {
const condition = { const condition = {
details: { details: {
@ -65,12 +63,10 @@ test('Pass condition not based on public_keys to makeOutput', t => {
t.deepEqual(res, expected) t.deepEqual(res, expected)
}) })
test('makeOutput throws TypeError with incorrect amount type', t => { 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 => { test('Create TRANSFER transaction based on CREATE transaction', t => {
sinon.spy(Transaction, 'makeTransaction') sinon.spy(Transaction, 'makeTransaction')
Transaction.makeTransferTransaction( Transaction.makeTransferTransaction(
@ -95,7 +91,6 @@ test('Create TRANSFER transaction based on CREATE transaction', t => {
Transaction.makeTransaction.restore() Transaction.makeTransaction.restore()
}) })
test('Create TRANSFER transaction based on TRANSFER transaction', t => { test('Create TRANSFER transaction based on TRANSFER transaction', t => {
sinon.spy(Transaction, 'makeTransaction') sinon.spy(Transaction, 'makeTransaction')

View File

@ -2,23 +2,23 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand */ /* eslint-disable strict, no-console, object-shorthand, import/no-extraneous-dependencies */
'use strict' 'use strict'
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin')
module.exports = { module.exports = {
devtool: 'inline-source-map', devtool: 'inline-source-map',
optimization: { optimization: {
minimizer: [ minimizer: [
new UglifyJsPlugin({ new TerserPlugin({
test: /vendor/, test: /vendor/,
sourceMap: false, sourceMap: false
}), }),
new UglifyJsPlugin({ new TerserPlugin({
test: /^((?!(vendor)).)*.js$/, test: /^((?!(vendor)).)*.js$/,
sourceMap: true, sourceMap: false
}) })
], ],
splitChunks: { splitChunks: {
@ -29,6 +29,6 @@ module.exports = {
chunks: 'all' chunks: 'all'
} }
} }
}, }
}, }
} }

View File

@ -2,12 +2,12 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0 // Code is Apache-2.0 and docs are CC-BY-4.0
/* eslint-disable strict, no-console, object-shorthand */ /* eslint-disable strict, no-console, object-shorthand, import/no-extraneous-dependencies */
'use strict' 'use strict'
const path = require('path') const path = require('path')
const merge = require('webpack-merge') const { merge } = require('webpack-merge')
const development = require('./webpack.development.js') const development = require('./webpack.development.js')
const production = require('./webpack.production.js') const production = require('./webpack.production.js')