diff --git a/docs/METHODS_EVENTS.md b/docs/METHODS_EVENTS.md new file mode 100644 index 0000000000..efdf06b0e1 --- /dev/null +++ b/docs/METHODS_EVENTS.md @@ -0,0 +1,214 @@ +## Events + +Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime. +- **[balances](#balances)** + +- **[contract](#contract)** + +- **[council](#council)** + +- **[councilMotions](#councilMotions)** + +- **[councilVoting](#councilVoting)** + +- **[democracy](#democracy)** + +- **[grandpa](#grandpa)** + +- **[indices](#indices)** + +- **[session](#session)** + +- **[staking](#staking)** + +- **[sudo](#sudo)** + +- **[system](#system)** + +- **[treasury](#treasury)** + + +___ + + +### balances + +▸ **NewAccount**(`AccountId`, `Balance`) +- **summary**: A new account was created. + +▸ **ReapedAccount**(`AccountId`) +- **summary**: An account was reaped. + +▸ **Transfer**(`AccountId`, `AccountId`, `Balance`, `Balance`) +- **summary**: Transfer succeeded (from, to, value, fees). + +___ + + +### contract + +▸ **CodeStored**(`Hash`) +- **summary**: Code with the specified hash has been stored. + +▸ **Dispatched**(`AccountId`, `bool`) +- **summary**: A call was dispatched from the given account. The bool signals whether it was successful execution or not. + +▸ **Instantiated**(`AccountId`, `AccountId`) +- **summary**: Contract deployed by address at the specified address. + +▸ **ScheduleUpdated**(`u32`) +- **summary**: Triggered when the current schedule is updated. + +▸ **Transfer**(`AccountId`, `AccountId`, `Balance`) +- **summary**: Transfer happened `from` to `to` with given `value` as part of a `call` or `create`. + +___ + + +### council + +▸ **BadReaperSlashed**(`AccountId`) +- **summary**: slashed reaper + +▸ **TallyFinalized**(`Vec`, `Vec`) +- **summary**: A tally (for approval votes of council seat(s)) has ended (with one or more new members). + +▸ **TallyStarted**(`u32`) +- **summary**: A tally (for approval votes of council seat(s)) has started. + +▸ **VoterReaped**(`AccountId`, `AccountId`) +- **summary**: reaped voter, reaper + +___ + + +### councilMotions + +▸ **Approved**(`Hash`) +- **summary**: A motion was approved by the required threshold. + +▸ **Disapproved**(`Hash`) +- **summary**: A motion was not approved by the required threshold. + +▸ **Executed**(`Hash`, `bool`) +- **summary**: A motion was executed; `bool` is true if returned without error. + +▸ **Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `u32`) +- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given u32). + +▸ **Voted**(`AccountId`, `Hash`, `bool`, `u32`, `u32`) +- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given as u32s respectively). + +___ + + +### councilVoting + +▸ **TallyCancelation**(`Hash`, `u32`, `u32`, `u32`) +- **summary**: A voting tally has happened for a referendum cancellation vote. Last three are yes, no, abstain counts. + +▸ **TallyReferendum**(`Hash`, `u32`, `u32`, `u32`) +- **summary**: A voting tally has happened for a referendum vote. Last three are yes, no, abstain counts. + +___ + + +### democracy + +▸ **Cancelled**(`ReferendumIndex`) + +▸ **Delegated**(`AccountId`, `AccountId`) + +▸ **Executed**(`ReferendumIndex`, `bool`) + +▸ **NotPassed**(`ReferendumIndex`) + +▸ **Passed**(`ReferendumIndex`) + +▸ **Proposed**(`PropIndex`, `Balance`) + +▸ **Started**(`ReferendumIndex`, `VoteThreshold`) + +▸ **Tabled**(`PropIndex`, `Balance`, `Vec`) + +▸ **Undelegated**(`AccountId`) + +___ + + +### grandpa + +▸ **NewAuthorities**(`Vec<(SessionKey,u64)>`) +- **summary**: New authority set has been applied. + +___ + + +### indices + +▸ **NewAccountIndex**(`AccountId`, `AccountIndex`) +- **summary**: A new account index was assigned. This event is not triggered when an existing index is reassigned to another `AccountId`. + +___ + + +### session + +▸ **NewSession**(`BlockNumber`) +- **summary**: New session has happened. Note that the argument is the session index, not the block number as the type might suggest. + +___ + + +### staking + +▸ **OfflineSlash**(`AccountId`, `Balance`) +- **summary**: One validator (and their nominators) has been slashed by the given amount. + +▸ **OfflineWarning**(`AccountId`, `u32`) +- **summary**: One validator (and their nominators) has been given a offline-warning (they're still within their grace). The accrued number of slashes is recorded, too. + +▸ **Reward**(`Balance`) +- **summary**: All validators have been rewarded by the given balance. + +___ + + +### sudo + +▸ **KeyChanged**(`AccountId`) +- **summary**: The sudoer just switched identity; the old key is supplied. + +▸ **Sudid**(`bool`) +- **summary**: A sudo just took place. + +___ + + +### system + +▸ **ExtrinsicFailed**() +- **summary**: An extrinsic failed. + +▸ **ExtrinsicSuccess**() +- **summary**: An extrinsic completed successfully. + +___ + + +### treasury + +▸ **Awarded**(`ProposalIndex`, `Balance`, `AccountId`) +- **summary**: Some funds have been allocated. + +▸ **Burnt**(`Balance`) +- **summary**: Some of our funds have been burnt. + +▸ **Proposed**(`ProposalIndex`) +- **summary**: New proposal. + +▸ **Rollover**(`Balance`) +- **summary**: Spending has finished; this is the amount that rolls over until next spend. + +▸ **Spending**(`Balance`) +- **summary**: We have ended a spend period and will now allocate funds. diff --git a/docs/METHODS_EXTRINSICS.md b/docs/METHODS_EXTRINSICS.md new file mode 100644 index 0000000000..e9a5dc34a8 --- /dev/null +++ b/docs/METHODS_EXTRINSICS.md @@ -0,0 +1,287 @@ +## Extrinsics + +_The following sections contain Extrinsics methods are part of the default Substrate runtime._ +- **[balances](#balances)** + +- **[consensus](#consensus)** + +- **[contract](#contract)** + +- **[council](#council)** + +- **[councilMotions](#councilMotions)** + +- **[councilVoting](#councilVoting)** + +- **[democracy](#democracy)** + +- **[finalityTracker](#finalityTracker)** + +- **[grandpa](#grandpa)** + +- **[session](#session)** + +- **[staking](#staking)** + +- **[sudo](#sudo)** + +- **[timestamp](#timestamp)** + +- **[treasury](#treasury)** + + +___ + + +### balances + +▸ **setBalance**(who: `Address`, free: `Compact`, reserved: `Compact`) +- **summary**: Set the balances of a given account. This will alter `FreeBalance` and `ReservedBalance` in storage. If the new free or reserved balance is below the existential deposit, it will also decrease the total issuance of the system (`TotalIssuance`) and reset the account nonce (`system::AccountNonce`). The dispatch origin for this call is `root`. + +▸ **transfer**(dest: `Address`, value: `Compact`) +- **summary**: Transfer some liquid free balance to another account. `transfer` will set the `FreeBalance` of the sender and receiver. It will decrease the total issuance of the system by the `TransferFee`. If the sender's account is below the existential deposit as a result of the transfer, the account will be reaped. The dispatch origin for this call must be `Signed` by the transactor. + +___ + + +### consensus + +▸ **killStorage**(keys: `Vec`) +- **summary**: Kill some items from storage. + +▸ **noteOffline**(offline: `InherentOfflineReport`) +- **summary**: Note the previous block's validator missed their opportunity to propose a block. + +▸ **remark**(_remark: `Bytes`) +- **summary**: Make some on-chain remark. + +▸ **reportMisbehavior**(_report: `Bytes`) +- **summary**: Report some misbehavior. + +▸ **setCode**(new: `Bytes`) +- **summary**: Set the new code. + +▸ **setHeapPages**(pages: `u64`) +- **summary**: Set the number of pages in the WebAssembly environment's heap. + +▸ **setStorage**(items: `Vec`) +- **summary**: Set some items of storage. + +___ + + +### contract + +▸ **call**(dest: `Address`, value: `Compact`, gas_limit: `Compact`, data: `Bytes`) +- **summary**: Makes a call to an account, optionally transferring some balance. * If the account is a smart-contract account, the associated code will be executed and any value will be transferred. * If the account is a regular account, any value will be transferred. * If no account exists and the call value is not less than `existential_deposit`, a regular account will be created and any value will be transferred. + +▸ **create**(endowment: `Compact`, gas_limit: `Compact`, code_hash: `CodeHash`, data: `Bytes`) +- **summary**: Creates a new contract from the `codehash` generated by `put_code`, optionally transferring some balance. Creation is executed as follows: - the destination address is computed based on the sender and hash of the code. - the smart-contract account is created at the computed address. - the `ctor_code` is executed in the context of the newly created account. Buffer returned after the execution is saved as the `code` of the account. That code will be invoked upon any call received by this account. - The contract is initialized. + +▸ **putCode**(gas_limit: `Compact`, code: `Bytes`) +- **summary**: Stores the given binary Wasm code into the chains storage and returns its `codehash`. You can instantiate contracts only with stored code. + +▸ **updateSchedule**(schedule: `Schedule`) +- **summary**: Updates the schedule for metering contracts. The schedule must have a greater version than the stored schedule. + +___ + + +### council + +▸ **presentWinner**(candidate: `Address`, total: `Compact`, index: `Compact`) +- **summary**: Claim that `signed` is one of the top Self::carry_count() + current_vote().1 candidates. Only works if the `block_number >= current_vote().0` and `< current_vote().0 + presentation_duration()`` `signed` should have at least + +▸ **reapInactiveVoter**(reporter_index: `Compact`, who: `Address`, who_index: `Compact`, assumed_vote_index: `Compact`) +- **summary**: Remove a voter. For it not to be a bond-consuming no-op, all approved candidate indices must now be either unregistered or registered to a candidate that registered the slot after the voter gave their last approval set. May be called by anyone. Returns the voter deposit to `signed`. + +▸ **removeMember**(who: `Address`) +- **summary**: Remove a particular member. A tally will happen instantly (if not already in a presentation period) to fill the seat if removal means that the desired members are not met. This is effective immediately. + +▸ **retractVoter**(index: `Compact`) +- **summary**: Remove a voter. All votes are cancelled and the voter deposit is returned. + +▸ **setApprovals**(votes: `Vec`, index: `Compact`) +- **summary**: Set candidate approvals. Approval slots stay valid as long as candidates in those slots are registered. + +▸ **setDesiredSeats**(count: `Compact`) +- **summary**: Set the desired member count; if lower than the current count, then seats will not be up election when they expire. If more, then a new vote will be started if one is not already in progress. + +▸ **setPresentationDuration**(count: `Compact`) +- **summary**: Set the presentation duration. If there is currently a vote being presented for, will invoke `finalize_vote`. + +▸ **setTermDuration**(count: `Compact`) +- **summary**: Set the presentation duration. If there is current a vote being presented for, will invoke `finalize_vote`. + +▸ **submitCandidacy**(slot: `Compact`) +- **summary**: Submit oneself for candidacy. Account must have enough transferrable funds in it to pay the bond. + +___ + + +### councilMotions + +▸ **propose**(threshold: `Compact`, proposal: `Proposal`) + +▸ **vote**(proposal: `Hash`, index: `Compact`, approve: `bool`) + +___ + + +### councilVoting + +▸ **propose**(proposal: `Proposal`) + +▸ **setCooloffPeriod**(blocks: `Compact`) + +▸ **setVotingPeriod**(blocks: `Compact`) + +▸ **veto**(proposal_hash: `Hash`) + +▸ **vote**(proposal: `Hash`, approve: `bool`) + +___ + + +### democracy + +▸ **cancelQueued**(when: `Compact`, which: `Compact`) +- **summary**: Cancel a proposal queued for enactment. + +▸ **cancelReferendum**(ref_index: `Compact`) +- **summary**: Remove a referendum. + +▸ **delegate**(to: `AccountId`, lock_periods: `LockPeriods`) +- **summary**: Delegate vote. + +▸ **propose**(proposal: `Proposal`, value: `Compact`) +- **summary**: Propose a sensitive action to be taken. + +▸ **second**(proposal: `Compact`) +- **summary**: Propose a sensitive action to be taken. + +▸ **startReferendum**(proposal: `Proposal`, threshold: `VoteThreshold`, delay: `BlockNumber`) +- **summary**: Start a referendum. + +▸ **undelegate**() +- **summary**: Undelegate vote. + +▸ **vote**(ref_index: `Compact`, vote: `Vote`) +- **summary**: Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo. + +___ + + +### finalityTracker + +▸ **finalHint**(hint: `Compact`) +- **summary**: Hint that the author of this block thinks the best finalized block is the given number. + +___ + + +### grandpa + +▸ **reportMisbehavior**(_report: `Bytes`) +- **summary**: Report some misbehavior. + +___ + + +### session + +▸ **forceNewSession**(apply_rewards: `bool`) +- **summary**: Forces a new session. + +▸ **setKey**(key: `SessionKey`) +- **summary**: Sets the session key of `_validator` to `_key`. This doesn't take effect until the next session. + +▸ **setLength**(new: `Compact`) +- **summary**: Set a new session length. Won't kick in until the next session change (at current length). + +___ + + +### staking + +▸ **bond**(controller: `Address`, value: `Compact`, payee: `RewardDestination`) +- **summary**: Take the origin account as a stash and lock up `value` of its balance. `controller` will be the account that controls it. The dispatch origin for this call must be _Signed_. + +▸ **bondExtra**(max_additional: `Compact`) +- **summary**: Add some extra amount that have appeared in the stash `free_balance` into the balance up for staking. Use this if there are additional funds in your stash account that you wish to bond. The dispatch origin for this call must be _Signed_ by the stash, not the controller. + +▸ **chill**() +- **summary**: Declare no desire to either validate or nominate. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. + +▸ **forceNewEra**(apply_rewards: `bool`) +- **summary**: Force there to be a new era. This also forces a new session immediately after. `apply_rewards` should be true for validators to get the session reward. + +▸ **nominate**(targets: `Vec
`) +- **summary**: Declare the desire to nominate `targets` for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. + +▸ **setBondingDuration**(new: `Compact`) +- **summary**: The length of the bonding duration in eras. + +▸ **setController**(controller: `Address`) +- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the stash, not the controller. + +▸ **setInvulnerables**(validators: `Vec`) +- **summary**: Set the validators who cannot be slashed (if any). + +▸ **setOfflineSlashGrace**(new: `Compact`) +- **summary**: Set the offline slash grace period. + +▸ **setPayee**(payee: `RewardDestination`) +- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. + +▸ **setSessionsPerEra**(new: `Compact`) +- **summary**: Set the number of sessions in an era. + +▸ **setValidatorCount**(new: `Compact`) +- **summary**: The ideal number of validators. + +▸ **unbond**(value: `Compact`) +- **summary**: Schedule a portion of the stash to be unlocked ready for transfer out after the bond period ends. If this leaves an amount actively bonded less than T::Currency::existential_deposit(), then it is increased to the full amount. Once the unlock period is done, you can call `withdraw_unbonded` to actually move the funds out of management ready for transfer. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::withdraw_unbonded`]. + +▸ **validate**(prefs: `ValidatorPrefs`) +- **summary**: Declare the desire to validate for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. + +▸ **withdrawUnbonded**() +- **summary**: Remove any unlocked chunks from the `unlocking` queue from our management. This essentially frees up that balance to be used by the stash account to do whatever it wants. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::unbond`]. + +___ + + +### sudo + +▸ **setKey**(new: `Address`) + +▸ **sudo**(proposal: `Proposal`) + +___ + + +### timestamp + +▸ **set**(now: `Compact`) +- **summary**: Set the current time. This call should be invoked exactly once per block. It will panic at the finalization phase, if this call hasn't been invoked by that time. The timestamp should be greater than the previous one by the amount specified by `minimum_period`. The dispatch origin for this call must be `Inherent`. + +___ + + +### treasury + +▸ **approveProposal**(proposal_id: `Compact`) +- **summary**: Approve a proposal. At a later time, the proposal will be allocated to the beneficiary and the original deposit will be returned. + +▸ **configure**(proposal_bond: `Compact`, proposal_bond_minimum: `Compact`, spend_period: `Compact`, burn: `Compact`) +- **summary**: (Re-)configure this module. + +▸ **proposeSpend**(value: `Compact`, beneficiary: `Address`) +- **summary**: Put forward a suggestion for spending. A deposit proportional to the value is reserved and slashed if the proposal is rejected. It is returned once the proposal is awarded. + +▸ **rejectProposal**(proposal_id: `Compact`) +- **summary**: Reject a proposed spend. The original deposit will be slashed. + +▸ **setPot**(new_pot: `Compact`) +- **summary**: Set the balance of funds available to spend. diff --git a/docs/METHODS_RPC.md b/docs/METHODS_RPC.md new file mode 100644 index 0000000000..62dac0aaa5 --- /dev/null +++ b/docs/METHODS_RPC.md @@ -0,0 +1,117 @@ +## JSON-RPC + +_The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit. The RPCs are provided by Substrate itself._ +- **[author](#author)** + +- **[chain](#chain)** + +- **[state](#state)** + +- **[system](#system)** + + +___ + + +### author + +_Authoring of network items_ + +▸ **pendingExtrinsics**(): `PendingExtrinsics` +- **summary**: Returns all pending extrinsics, potentially grouped by sender + +▸ **submitAndWatchExtrinsic**(extrinsic: `Extrinsic`): `ExtrinsicStatus` +- **summary**: Subscribe and watch an extrinsic until unsubscribed + +▸ **submitExtrinsic**(extrinsic: `Extrinsic`): `Hash` +- **summary**: Submit a fully formatted extrinsic for block inclusion + +___ + + +### chain + +_Retrieval of chain data_ + +▸ **getBlock**(hash?: `Hash`): `SignedBlock` +- **summary**: Get header and body of a relay chain block + +▸ **getBlockHash**(blockNumber?: `BlockNumber`): `Hash` +- **summary**: Get the block hash for a specific block + +▸ **getFinalizedHead**(): `Hash` +- **summary**: Get hash of the last finalised block in the canon chain + +▸ **getHeader**(hash?: `Hash`): `Header` +- **summary**: Retrieves the header for a specific block + +▸ **getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion` +- **summary**: Get the runtime version (alias of state_getRuntimeVersion) + +▸ **subscribeFinalizedHeads**(): `Header` +- **summary**: Retrieves the best finalized header via subscription + +▸ **subscribeNewHead**(): `Header` +- **summary**: Retrieves the best header via subscription + +▸ **subscribeRuntimeVersion**(): `RuntimeVersion` +- **summary**: Retrieves the runtime version via subscription + +___ + + +### state + +_Query of state_ + +▸ **call**(method: `Text`, data: `Bytes`, block?: `Hash`): `Bytes` +- **summary**: Perform a call to a builtin on the chain + +▸ **getMetadata**(block?: `Hash`): `Metadata` +- **summary**: Returns the runtime metadata + +▸ **getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion` +- **summary**: Get the runtime version + +▸ **getStorage**(key: `StorageKey`, block?: `Hash`): `StorageData` +- **summary**: Retrieves the storage for a key + +▸ **getStorageHash**(key: `StorageKey`, block?: `Hash`): `Hash` +- **summary**: Retrieves the storage hash + +▸ **getStorageSize**(key: `StorageKey`, block?: `Hash`): `u64` +- **summary**: Retrieves the storage size + +▸ **queryStorage**(keys: `Vec`, startBlock: `Hash`, block?: `Hash`): `Vec` +- **summary**: Query historical storage entries (by key) starting from a start block + +▸ **subscribeStorage**(keys: `Vec`): `StorageChangeSet` +- **summary**: Subscribes to storage changes for the provided keys + +___ + + +### system + +_Methods to retrieve system info_ + +▸ **chain**(): `Text` +- **summary**: Retrieves the chain + +▸ **health**(): `Health` +- **summary**: Return health status of the node + +▸ **name**(): `Text` +- **summary**: Retrieves the node name + +▸ **networkState**(): `NetworkState` +- **summary**: Returns current state of the network + +▸ **peers**(): `Vec` +- **summary**: Returns the currently connected peers + +▸ **properties**(): `ChainProperties` +- **summary**: Get a custom set of properties as a JSON object, defined in the chain spec + +▸ **version**(): `Text` +- **summary**: Retrieves the version of the node diff --git a/docs/METHODS_STORAGE.md b/docs/METHODS_STORAGE.md new file mode 100644 index 0000000000..79ed58107d --- /dev/null +++ b/docs/METHODS_STORAGE.md @@ -0,0 +1,529 @@ +## Storage + +_The following sections contain Storage methods are part of the default Substrate runtime._ +- **[balances](#balances)** + +- **[consensus](#consensus)** + +- **[contract](#contract)** + +- **[council](#council)** + +- **[councilMotions](#councilMotions)** + +- **[councilVoting](#councilVoting)** + +- **[democracy](#democracy)** + +- **[grandpaFinality](#grandpaFinality)** + +- **[indices](#indices)** + +- **[session](#session)** + +- **[staking](#staking)** + +- **[sudo](#sudo)** + +- **[system](#system)** + +- **[timestamp](#timestamp)** + +- **[treasury](#treasury)** + +- **[substrate](#substrate)** + + +___ + + +### balances + +▸ **creationFee**(): `Balance` +- **summary**: The fee required to create an account. + +▸ **existentialDeposit**(): `Balance` +- **summary**: The minimum amount required to keep an account open. + +▸ **freeBalance**(`AccountId`): `Balance` +- **summary**: The 'free' balance of a given account. This is the only balance that matters in terms of most operations on tokens. It alone is used to determine the balance when in the contract execution environment. When this balance falls below the value of `ExistentialDeposit`, then the 'current account' is deleted: specifically `FreeBalance`. Further, the `OnFreeBalanceZero` callback is invoked, giving a chance to external modules to clean up data associated with the deleted account. `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`. + +▸ **locks**(`AccountId`): `Vec` +- **summary**: Any liquidity locks on some account balances. + +▸ **reservedBalance**(`AccountId`): `Balance` +- **summary**: The amount of the balance of a given account that is externally reserved; this can still get slashed, but gets slashed last of all. This balance is a 'reserve' balance that other subsystems use in order to set aside tokens that are still 'owned' by the account holder, but which are suspendable. When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' is deleted: specifically, `ReservedBalance`. `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.) + +▸ **totalIssuance**(): `Balance` +- **summary**: The total units issued in the system. + +▸ **transactionBaseFee**(): `Balance` +- **summary**: The fee to be paid for making a transaction; the base. + +▸ **transactionByteFee**(): `Balance` +- **summary**: The fee to be paid for making a transaction; the per-byte portion. + +▸ **transferFee**(): `Balance` +- **summary**: The fee required to make a transfer. + +▸ **vesting**(`AccountId`): `Option` +- **summary**: Information regarding the vesting of a given account. + +___ + + +### consensus + +▸ **originalAuthorities**(): `Option>` + +___ + + +### contract + +▸ **accountCounter**(): `u64` +- **summary**: The subtrie counter + +▸ **accountInfoOf**(`AccountId`): `Option` +- **summary**: The code associated with a given account. + +▸ **blockGasLimit**(): `Gas` +- **summary**: The maximum amount of gas that could be expended per block. + +▸ **callBaseFee**(): `Gas` +- **summary**: The base fee charged for calling into a contract. + +▸ **codeHashOf**(`AccountId`): `Option` +- **summary**: The code associated with a given account. + +▸ **codeStorage**(`CodeHash`): `Option` +- **summary**: A mapping between an original code hash and instrumented wasm code, ready for the execution. + +▸ **contractFee**(): `BalanceOf` +- **summary**: The fee required to create a contract instance. + +▸ **createBaseFee**(): `Gas` +- **summary**: The base fee charged for creating a contract. + +▸ **creationFee**(): `BalanceOf` +- **summary**: The fee required to create an account. + +▸ **currentSchedule**(): `Schedule` +- **summary**: Current cost schedule for contracts. + +▸ **gasPrice**(): `BalanceOf` +- **summary**: The price of one unit of gas. + +▸ **gasSpent**(): `Gas` +- **summary**: Gas spent so far in this block. + +▸ **maxDepth**(): `u32` +- **summary**: The maximum nesting level of a call/create stack. + +▸ **pristineCode**(`CodeHash`): `Option` +- **summary**: A mapping from an original code hash to the original code, untouched by instrumentation. + +▸ **transactionBaseFee**(): `BalanceOf` +- **summary**: The fee to be paid for making a transaction; the base. + +▸ **transactionByteFee**(): `BalanceOf` +- **summary**: The fee to be paid for making a transaction; the per-byte portion. + +▸ **transferFee**(): `BalanceOf` +- **summary**: The fee required to make a transfer. + +___ + + +### council + +▸ **activeCouncil**(): `Vec<(AccountId,BlockNumber)>` +- **summary**: The current council. When there's a vote going on, this should still be used for executive matters. The block number (second element in the tuple) is the block that their position is active until (calculated by the sum of the block number when the council member was elected and their term duration). + +▸ **approvalsOf**(`AccountId`): `Vec` +- **summary**: A list of votes for each voter, respecting the last cleared vote index that this voter was last active at. + +▸ **candidacyBond**(): `BalanceOf` +- **summary**: How much should be locked up in order to submit one's candidacy. + +▸ **candidateCount**(): `u32` + +▸ **candidates**(): `Vec` +- **summary**: The present candidate list. + +▸ **carryCount**(): `u32` +- **summary**: How many runners-up should have their approvals persist until the next vote. + +▸ **desiredSeats**(): `u32` +- **summary**: Number of accounts that should be sitting on the council. + +▸ **inactiveGracePeriod**(): `VoteIndex` +- **summary**: How many vote indexes need to go by after a target voter's last vote before they can be reaped if their approvals are moot. + +▸ **lastActiveOf**(`AccountId`): `Option` +- **summary**: The last cleared vote index that this voter was last active at. + +▸ **leaderboard**(): `Option>` +- **summary**: Get the leaderboard if we;re in the presentation phase. + +▸ **nextFinalize**(): `Option<(BlockNumber,u32,Vec)>` +- **summary**: The accounts holding the seats that will become free on the next tally. + +▸ **presentSlashPerVoter**(): `BalanceOf` +- **summary**: The punishment, per voter, if you provide an invalid presentation. + +▸ **presentationDuration**(): `BlockNumber` +- **summary**: How long to give each top candidate to present themselves after the vote ends. + +▸ **registerInfoOf**(`AccountId`): `Option<(VoteIndex,u32)>` +- **summary**: The vote index and list slot that the candidate `who` was registered or `None` if they are not currently registered. + +▸ **snapshotedStakes**(): `Vec` +- **summary**: The stakes as they were at the point that the vote ended. + +▸ **termDuration**(): `BlockNumber` +- **summary**: How long each position is active for. + +▸ **voteCount**(): `VoteIndex` +- **summary**: The total number of votes that have happened or are in progress. + +▸ **voters**(): `Vec` +- **summary**: The present voter list. + +▸ **votingBond**(): `BalanceOf` +- **summary**: How much should be locked up in order to be able to submit votes. + +▸ **votingPeriod**(): `BlockNumber` +- **summary**: How often (in blocks) to check for new votes. + +___ + + +### councilMotions + +▸ **proposalCount**(): `u32` +- **summary**: Proposals so far. + +▸ **proposalOf**(`Hash`): `Option` +- **summary**: Actual proposal for a given hash, if it's current. + +▸ **proposals**(): `Vec` +- **summary**: The (hashes of) the active proposals. + +▸ **voting**(`Hash`): `Option<(ProposalIndex,u32,Vec,Vec)>` +- **summary**: Votes for a given proposal: (required_yes_votes, yes_voters, no_voters). + +___ + + +### councilVoting + +▸ **cooloffPeriod**(): `BlockNumber` + +▸ **councilVoteOf**(`(Hash,AccountId)`): `Option` + +▸ **enactDelayPeriod**(): `BlockNumber` +- **summary**: Number of blocks by which to delay enactment of successful, non-unanimous-council-instigated referendum proposals. + +▸ **proposalOf**(`Hash`): `Option` + +▸ **proposalVoters**(`Hash`): `Vec` + +▸ **proposals**(): `Vec<(BlockNumber,Hash)>` + +▸ **vetoedProposal**(`Hash`): `Option<(BlockNumber,Vec)>` + +▸ **votingPeriod**(): `BlockNumber` + +___ + + +### democracy + +▸ **delegations**(`AccountId`): `((AccountId,LockPeriods), Linkage)` +- **summary**: Get the account (and lock periods) to which another account is delegating vote. + +▸ **depositOf**(`PropIndex`): `Option<(BalanceOf,Vec)>` +- **summary**: Those who have locked a deposit. + +▸ **dispatchQueue**(`BlockNumber`): `Vec>` +- **summary**: Queue of successful referenda to be dispatched. + +▸ **launchPeriod**(): `BlockNumber` +- **summary**: How often (in blocks) new public referenda are launched. + +▸ **maxLockPeriods**(): `LockPeriods` +- **summary**: The maximum number of additional lock periods a voter may offer to strengthen their vote. Multiples of `PublicDelay`. + +▸ **minimumDeposit**(): `BalanceOf` +- **summary**: The minimum amount to be used as a deposit for a public referendum proposal. + +▸ **nextTally**(): `ReferendumIndex` +- **summary**: The next referendum index that should be tallied. + +▸ **publicDelay**(): `BlockNumber` +- **summary**: The delay before enactment for all public referenda. + +▸ **publicPropCount**(): `PropIndex` +- **summary**: The number of (public) proposals that have been made so far. + +▸ **publicProps**(): `Vec<(PropIndex,Proposal,AccountId)>` +- **summary**: The public proposals. Unsorted. + +▸ **referendumCount**(): `ReferendumIndex` +- **summary**: The next free referendum index, aka the number of referendums started so far. + +▸ **referendumInfoOf**(`ReferendumIndex`): `Option` +- **summary**: Information concerning any given referendum. + +▸ **voteOf**(`(ReferendumIndex,AccountId)`): `Vote` +- **summary**: Get the vote in a given referendum of a particular voter. The result is meaningful only if `voters_for` includes the voter when called with the referendum (you'll get the default `Vote` value otherwise). If you don't want to check `voters_for`, then you can also check for simple existence with `VoteOf::exists` first. + +▸ **votersFor**(`ReferendumIndex`): `Vec` +- **summary**: Get the voters for the current proposal. + +▸ **votingPeriod**(): `BlockNumber` +- **summary**: How often (in blocks) to check for new votes. + +___ + + +### grandpaFinality + +▸ **nextForced**(): `Option` + +▸ **pendingChange**(): `Option` + +___ + + +### indices + +▸ **enumSet**(`AccountIndex`): `Vec` +- **summary**: The enumeration sets. + +▸ **nextEnumSet**(): `AccountIndex` +- **summary**: The next free enumeration set. + +___ + + +### session + +▸ **currentIndex**(): `BlockNumber` +- **summary**: Current index of the session. + +▸ **currentStart**(): `Moment` +- **summary**: Timestamp when current session started. + +▸ **forcingNewSession**(): `Option` +- **summary**: New session is being forced is this entry exists; in which case, the boolean value is whether the new session should be considered a normal rotation (rewardable) or exceptional (slashable). + +▸ **lastLengthChange**(): `Option` +- **summary**: Block at which the session length last changed. + +▸ **nextKeyFor**(`AccountId`): `Option` +- **summary**: The next key for a given validator. + +▸ **nextSessionLength**(): `Option` +- **summary**: The next session length. + +▸ **sessionLength**(): `BlockNumber` +- **summary**: Current length of the session. + +▸ **validators**(): `Vec` +- **summary**: The current set of validators. + +___ + + +### staking + +▸ **bonded**(`AccountId`): `Option` +- **summary**: Map from all locked "stash" accounts to the controller account. + +▸ **bondingDuration**(): `BlockNumber` +- **summary**: The length of the bonding duration in blocks. + +▸ **currentElected**(): `Vec` +- **summary**: The currently elected validator set keyed by stash account ID. + +▸ **currentEra**(): `BlockNumber` +- **summary**: The current era index. + +▸ **currentEraReward**(): `BalanceOf` +- **summary**: The accumulated reward for the current era. Reset to zero at the beginning of the era and increased for every successfully finished session. + +▸ **currentSessionReward**(): `BalanceOf` +- **summary**: Maximum reward, per validator, that is provided per acceptable session. + +▸ **forcingNewEra**(): `Option` +- **summary**: We are forcing a new era. + +▸ **invulnerables**(): `Vec` +- **summary**: Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialize and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets. + +▸ **lastEraLengthChange**(): `BlockNumber` +- **summary**: The session index at which the era length last changed. + +▸ **ledger**(`AccountId`): `Option` +- **summary**: Map from all (unlocked) "controller" accounts to the info regarding the staking. + +▸ **minimumValidatorCount**(): `u32` +- **summary**: Minimum number of staking participants before emergency conditions are imposed. + +▸ **nextSessionsPerEra**(): `Option` +- **summary**: The next value of sessions per era. + +▸ **nominators**(`AccountId`): `(Vec, Linkage)` +- **summary**: The map from nominator stash key to the set of stash keys of all validators to nominate. + +▸ **offlineSlash**(): `Perbill` +- **summary**: Slash, per validator that is taken for the first time they are found to be offline. + +▸ **offlineSlashGrace**(): `u32` +- **summary**: Number of instances of offline reports before slashing begins for validators. + +▸ **payee**(`AccountId`): `RewardDestination` +- **summary**: Where the reward payment should be made. Keyed by stash. + +▸ **recentlyOffline**(): `Vec<(AccountId,BlockNumber,u32)>` +- **summary**: Most recent `RECENT_OFFLINE_COUNT` instances. (who it was, when it was reported, how many instances they were offline for). + +▸ **sessionReward**(): `Perbill` +- **summary**: Maximum reward, per validator, that is provided per acceptable session. + +▸ **sessionsPerEra**(): `BlockNumber` +- **summary**: The length of a staking era in sessions. + +▸ **slashCount**(`AccountId`): `u32` +- **summary**: The number of times a given validator has been reported offline. This gets decremented by one each era that passes. + +▸ **slotStake**(): `BalanceOf` +- **summary**: The amount of balance actively at stake for each validator slot, currently. This is used to derive rewards and punishments. + +▸ **stakers**(`AccountId`): `Exposure` +- **summary**: Nominators for a particular account that is in action right now. You can't iterate through validators here, but you can find them in the `sessions` module. This is keyed by the stash account. + +▸ **validatorCount**(): `u32` +- **summary**: The ideal number of staking participants. + +▸ **validators**(`AccountId`): `(ValidatorPrefs, Linkage)` +- **summary**: The map from (wannabe) validator stash key to the preferences of that validator. + +___ + + +### sudo + +▸ **key**(): `AccountId` + +___ + + +### system + +▸ **accountNonce**(`AccountId`): `Index` +- **summary**: Extrinsics nonce for accounts. + +▸ **allExtrinsicsLen**(): `Option` +- **summary**: Total length in bytes for all extrinsics put together, for the current block. + +▸ **blockHash**(`BlockNumber`): `Hash` +- **summary**: Map of block numbers to block hashes. + +▸ **digest**(): `Digest` +- **summary**: Digest of the current block, also part of the block header. + +▸ **events**(): `Vec` +- **summary**: Events deposited for the current block. + +▸ **extrinsicCount**(): `Option` +- **summary**: Total extrinsics count for the current block. + +▸ **extrinsicData**(`u32`): `Bytes` +- **summary**: Extrinsics data for the current block (maps extrinsic's index to its data). + +▸ **extrinsicsRoot**(): `Hash` +- **summary**: Extrinsics root of the current block, also part of the block header. + +▸ **number**(): `BlockNumber` +- **summary**: The current block number being processed. Set by `execute_block`. + +▸ **parentHash**(): `Hash` +- **summary**: Hash of the previous block. + +▸ **randomSeed**(): `Hash` +- **summary**: Random seed of the current block. + +___ + + +### timestamp + +▸ **blockPeriod**(): `Option` +- **summary**: Old storage item provided for compatibility. Remove after all networks upgraded. + +▸ **didUpdate**(): `bool` +- **summary**: Did the timestamp get updated in this block? + +▸ **minimumPeriod**(): `Moment` +- **summary**: The minimum period between blocks. Beware that this is different to the *expected* period that the block production apparatus provides. Your chosen consensus system will generally work with this to determine a sensible block time. e.g. For Aura, it will be double this period on default settings. + +▸ **now**(): `Moment` +- **summary**: Current time for the current block. + +___ + + +### treasury + +▸ **approvals**(): `Vec` +- **summary**: Proposal indices that have been approved but not yet awarded. + +▸ **burn**(): `Permill` +- **summary**: Percentage of spare funds (if any) that are burnt per spend period. + +▸ **pot**(): `BalanceOf` +- **summary**: Total funds available to this module for spending. + +▸ **proposalBond**(): `Permill` +- **summary**: Proportion of funds that should be bonded in order to place a proposal. An accepted proposal gets these back. A rejected proposal doesn't. + +▸ **proposalBondMinimum**(): `BalanceOf` +- **summary**: Minimum amount of funds that should be placed in a deposit for making a proposal. + +▸ **proposalCount**(): `ProposalIndex` +- **summary**: Number of proposals that have been made. + +▸ **proposals**(`ProposalIndex`): `Option` +- **summary**: Proposals that have been made. + +▸ **spendPeriod**(): `BlockNumber` +- **summary**: Period between successive spends. + +--- + +### substrate + +_These are keys that are always available to the runtime implementation_ + +▸ **authorityCount**(): `u32` +- **summary**: Number of authorities. + +▸ **authorityPrefix**(): `u32` +- **summary**: Prefix under which authorities are storied. + +▸ **changesTrieConfig**(): `u32` +- **summary**: Changes trie configuration is stored under this key. + +▸ **code**(): `Bytes` +- **summary**: Wasm code of the runtime. + +▸ **extrinsicIndex**(): `u32` +- **summary**: Current extrinsic index (u32) is stored under this key. + +▸ **heapPages**(): `u64` +- **summary**: Number of wasm linear memory pages required for execution of the runtime. + +--- diff --git a/jest.config.js b/jest.config.js index 8db5888298..4cffdcc9de 100644 --- a/jest.config.js +++ b/jest.config.js @@ -8,10 +8,7 @@ module.exports = Object.assign({}, config, { '@plugnet/extrinsics(.*)$': '/packages/type-extrinsics/src/$1', '@plugnet/jsonrpc(.*)$': '/packages/type-jsonrpc/src/$1', '@plugnet/storage(.*)$': '/packages/type-storage/src/$1', - '@plugnet/types(.*)$': '/packages/types/src/$1', - '@plugnet/keyring(.*)$': '/packages/keyring/src/$1', - '@plugnet/util(.*)$': '/packages/util/src/$1', - '@plugnet/util-crypto(.*)$': '/packages/util-crypto/src/$1' + '@plugnet/types(.*)$': '/packages/types/src/$1' }, modulePathIgnorePatterns: [ '/packages/api/build', @@ -22,9 +19,6 @@ module.exports = Object.assign({}, config, { '/packages/type-extrinsics/build', '/packages/type-jsonrpc/build', '/packages/type-storage/build/', - '/packages/types/build', - '/packages/keyring/build', - '/packages/util/build/', - '/packages/util-crypto/build' + '/packages/types/build' ] }); diff --git a/package.json b/package.json index e34163d9e3..b6f4988a8f 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "@babel/core": "^7.4.3", "@babel/register": "^7.4.0", "@babel/runtime": "^7.4.3", - "@plugnet/dev": "file:///Users/moge/Workspace/centrality/plug/plugnet-js-dev/packages/dev/build", + "@plugnet/dev": "^0.30.0", "@polkadot/ts": "^0.1.56", "gh-pages": "^2.0.1" } diff --git a/packages/api/README.md b/packages/api/README.md index d8c33d9a39..00d25bd819 100644 --- a/packages/api/README.md +++ b/packages/api/README.md @@ -1,4 +1,4 @@ -# @polkadot/api +# @plugnet/api The Polkadot-JS API provides easy-to-use wrappers around JSONRPC calls that flow from an application to a node. It handles all the encoding and decoding or parameters, provides access to RPC functions and allows for the query of chain state and the submission of transactions. diff --git a/packages/api/package.json b/packages/api/package.json index 9f7aa67b36..d8acf96d7f 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -36,6 +36,6 @@ "@plugnet/rpc-rx": "^0.76.1", "@plugnet/storage": "^0.76.1", "@plugnet/types": "^0.76.1", - "@plugnet/util-crypto": "^0.76.1" + "@plugnet/util-crypto": "^0.76.2-beta.0" } } diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index eb0d5b54bd..5cd3782b2c 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -51,7 +51,7 @@ try { pkgJson = require('./package.json'); } catch (error) { // development environment - pkgJson = { name: '@polkadot/api', version: '-' }; + pkgJson = { name: '@plugnet/api', version: '-' }; } /** diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 67a94c3630..4220a3712c 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -5,7 +5,7 @@ export { WsProvider } from '@plugnet/rpc-provider'; import { assertSingletonPackage } from '@plugnet/util'; -assertSingletonPackage('@polkadot/api'); +assertSingletonPackage('@plugnet/api'); export { default as ApiPromise } from './promise'; export { default as ApiRx } from './rx'; diff --git a/packages/api/src/promise/Api.ts b/packages/api/src/promise/Api.ts index f37ea8a3dd..4535bcb31a 100644 --- a/packages/api/src/promise/Api.ts +++ b/packages/api/src/promise/Api.ts @@ -16,7 +16,7 @@ import ApiBase from '../Base'; import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator'; /** - * # @polkadot/api/promise + * # @plugnet/api/promise * * ## Overview * diff --git a/packages/api/src/rx/Api.ts b/packages/api/src/rx/Api.ts index 009844357e..eacf4a2d7d 100644 --- a/packages/api/src/rx/Api.ts +++ b/packages/api/src/rx/Api.ts @@ -12,7 +12,7 @@ import { Observable, from } from 'rxjs'; import ApiBase from '../Base'; /** - * # @polkadot/api/rx + * # @plugnet/api/rx * * ## Overview * diff --git a/packages/api/test/e2e/promise-contract.spec.js b/packages/api/test/e2e/promise-contract.spec.js index 3583325a00..e7a9b7eb01 100644 --- a/packages/api/test/e2e/promise-contract.spec.js +++ b/packages/api/test/e2e/promise-contract.spec.js @@ -5,8 +5,8 @@ import fs from 'fs'; import path from 'path'; -import { ContractAbi } from '@polkadot/types'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import { ContractAbi } from '@plugnet/types'; +import testingPairs from '@plugnet/keyring/testingPairs'; import json from '../data/erc20.json'; import Api from '../../src/promise'; diff --git a/packages/api/test/e2e/promise-queries.spec.js b/packages/api/test/e2e/promise-queries.spec.js index 4ec9c9b21b..4e58bb7fd8 100644 --- a/packages/api/test/e2e/promise-queries.spec.js +++ b/packages/api/test/e2e/promise-queries.spec.js @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import BN from 'bn.js'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import testingPairs from '@plugnet/keyring/testingPairs'; import Api from '../../src/promise'; diff --git a/packages/api/test/e2e/promise-tx.spec.js b/packages/api/test/e2e/promise-tx.spec.js index 6566161a19..de1ff22fd5 100644 --- a/packages/api/test/e2e/promise-tx.spec.js +++ b/packages/api/test/e2e/promise-tx.spec.js @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Keyring from '@polkadot/keyring'; -import testingPairs from '@polkadot/keyring/testingPairs'; -import { randomAsHex } from '@polkadot/util-crypto'; +import Keyring from '@plugnet/keyring'; +import testingPairs from '@plugnet/keyring/testingPairs'; +import { randomAsHex } from '@plugnet/util-crypto'; import Api from '../../src/promise'; import WsProvider from '../../../rpc-provider/src/ws'; diff --git a/packages/api/test/e2e/rx-queries.spec.js b/packages/api/test/e2e/rx-queries.spec.js index 1796f7a4a4..10923b0129 100644 --- a/packages/api/test/e2e/rx-queries.spec.js +++ b/packages/api/test/e2e/rx-queries.spec.js @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { switchMap } from 'rxjs/operators'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import testingPairs from '@plugnet/keyring/testingPairs'; import Api from '../../src/rx'; diff --git a/packages/api/test/e2e/rx-tx.spec.js b/packages/api/test/e2e/rx-tx.spec.js index 98957602f9..6e529052f7 100644 --- a/packages/api/test/e2e/rx-tx.spec.js +++ b/packages/api/test/e2e/rx-tx.spec.js @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { first, switchMap } from 'rxjs/operators'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import testingPairs from '@plugnet/keyring/testingPairs'; import Api from '../../src/rx'; diff --git a/packages/keyring/LICENSE b/packages/keyring/LICENSE deleted file mode 100644 index 0d381b2e97..0000000000 --- a/packages/keyring/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -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. diff --git a/packages/keyring/README.md b/packages/keyring/README.md deleted file mode 100644 index 3ad57647fb..0000000000 --- a/packages/keyring/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# @polkadot/keyring - -Key management of user accounts including generation and retrieval of keyring pairs from a variety of input combinations. - -## Usage - -Installation - - -``` -yarn add @polkadot/keyring -``` - -Classes and Functions can be imported as follows: - -```js -import Keyring from '@polkadot/keyring'; -``` - -## Utilities - -[Utilities](SUMMARY.md) diff --git a/packages/keyring/package.json b/packages/keyring/package.json deleted file mode 100644 index 2af5883a19..0000000000 --- a/packages/keyring/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@plugnet/keyring", - "version": "0.76.1", - "description": "Keyring management", - "main": "index.js", - "engines": { - "node": ">=8.0" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/polkadot-js/common.git" - }, - "keywords": [ - "Plugnet", - "Keyring", - "ed25519" - ], - "author": "Jaco Greeff ", - "maintainers": [ - "Jaco Greeff " - ], - "contributors": [], - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/polkadot-js/common/issues" - }, - "homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme", - "dependencies": { - "@babel/runtime": "^7.4.3", - "@plugnet/util": "^0.76.1", - "@plugnet/util-crypto": "^0.76.1", - "@types/bs58": "^4.0.0", - "bs58": "^4.0.1" - } -} diff --git a/packages/keyring/src/address/decode.spec.ts b/packages/keyring/src/address/decode.spec.ts deleted file mode 100644 index f985de54bd..0000000000 --- a/packages/keyring/src/address/decode.spec.ts +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. -// @flow - -import testingPairs from '../testingPairs'; -import decode from './decode'; - -describe('decode', () => { - let keyring: any; - - beforeAll(async () => { - keyring = testingPairs({ type: 'sr25519' }); - }); - - it('decodes an address', () => { - expect( - decode('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY') - ).toEqual( - keyring.alice.publicKey() - ); - }); - - it('converts a publicKey (u8a) as-is', () => { - expect( - decode(new Uint8Array([1, 2, 3])) - ).toEqual( - new Uint8Array([1, 2, 3]) - ); - }); - - it('converts a publicKey (hex) as-is', () => { - expect( - decode('0x01020304') - ).toEqual( - new Uint8Array([1, 2, 3, 4]) - ); - }); - - it('decodes a short address', () => { - expect( - decode('F7NZ') - ).toEqual(new Uint8Array([1])); - }); - - it('decodes a 1-byte accountId (with prefix)', () => { - expect( - decode('PqtB', false, 68) - ).toEqual(new Uint8Array([1])); - }); - - it('decodes a 2-byte accountId', () => { - expect( - decode('2jpAFn', false, 68) - ).toEqual(new Uint8Array([0, 1])); - }); - - it('encodes a 4-byte address', () => { - expect( - decode('as7QnGMf', false, 68) - ).toEqual(new Uint8Array([1, 2, 3, 4])); - }); - - it('decodes a 8-byte address', () => { - expect( - decode('4q7qY5RBG7Z4wv', false, 68) - ).toEqual(new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0])); - }); - - it.skip('allows invalid prefix (in list)', () => { - expect( - () => decode('6GfvWUvHvU8otbZ7sFhXH4eYeMcKdUkL61P3nFy52efEPVUx') - ).toThrow(/address prefix/); - }); - - it('fails when length is invalid', () => { - expect( - () => decode('y9EMHt34JJo4rWLSaxoLGdYXvjgSXEd4zHUnQgfNzwES8b') - ).toThrow(/address length/); - }); - - it('fails when the checksum does not match', () => { - expect( - () => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMa9cj') - ).toThrow(/address checksum/); - expect( - () => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU') - ).toThrow(/address checksum/); - }); -}); diff --git a/packages/keyring/src/address/decode.ts b/packages/keyring/src/address/decode.ts deleted file mode 100644 index 7f4d74b015..0000000000 --- a/packages/keyring/src/address/decode.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Prefix } from './types'; - -// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6 - -import bs58 from 'bs58'; -import { assert, bufferToU8a, isHex, isU8a, u8aToU8a } from '@plugnet/util'; - -import defaults from './defaults'; -import sshash from './sshash'; - -export default function decode (encoded: string | Uint8Array, ignoreChecksum?: boolean, prefix: Prefix = defaults.prefix): Uint8Array { - if (isU8a(encoded) || isHex(encoded)) { - return u8aToU8a(encoded); - } - - const decoded = bufferToU8a(bs58.decode(encoded)); - const error = (message: string) => - `Decoding ${encoded}: ${message}`; - - // assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix')); - assert(defaults.allowedEncodedLengths.includes(decoded.length), error('Invalid decoded address length')); - - // TODO Unless it is an "use everywhere" prefix, throw an error - // if (decoded[0] !== prefix) { - // console.log(`WARN: Expected ${prefix}, found ${decoded[0]}`); - // } - - const isPublicKey = decoded.length === 35; - - // non-publicKeys has 1 byte checksums, else default to 2 - const endPos = decoded.length - (isPublicKey ? 2 : 1); - - // calculate the hash and do the checksum byte checks - const hash = sshash(decoded.subarray(0, endPos)); - const checks = isPublicKey - ? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1] - : decoded[decoded.length - 1] === hash[0]; - - assert(ignoreChecksum || checks, error('Invalid decoded address checksum')); - - return decoded.slice(1, endPos); -} diff --git a/packages/keyring/src/address/defaults.ts b/packages/keyring/src/address/defaults.ts deleted file mode 100644 index 0d7861c2b3..0000000000 --- a/packages/keyring/src/address/defaults.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Prefix } from './types'; - -const defaults = { - allowedDecodedLengths: [1, 2, 4, 8, 32], - // publicKey has prefix + 2 checksum bytes, short only prefix + 1 checksum byte - allowedEncodedLengths: [3, 4, 6, 10, 35], - allowedPrefix: [0, 1, 3, 42, 43, 68, 69] as Array, - prefix: 42 as Prefix -}; - -export default defaults; diff --git a/packages/keyring/src/address/encode.spec.ts b/packages/keyring/src/address/encode.spec.ts deleted file mode 100644 index 2e39dfb24b..0000000000 --- a/packages/keyring/src/address/encode.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. -// @flow - -import testingPairs from '../testingPairs'; -import encode from './encode'; - -const keyring = testingPairs({ type: 'ed25519' }, false); - -describe('encode', () => { - it('encodes an address to a valid value', () => { - expect( - keyring.alice.address() - ).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'); - }); - - it('fails when non-valid publicKey provided', () => { - expect( - () => encode( - keyring.alice.publicKey().slice(0, 30) - ) - ).toThrow(/Expected a valid key/); - }); - - it('encodes a 1-byte address', () => { - expect( - encode( - new Uint8Array([1]) - ) - ).toEqual('F7NZ'); - }); - - it('encodes a 1-byte address (with prefix)', () => { - expect( - encode( - new Uint8Array([1]), 68 - ) - ).toEqual('PqtB'); - }); - - it('encodes a 2-byte address', () => { - expect( - encode( - new Uint8Array([0, 1]), 68 - ) - ).toEqual('2jpAFn'); - }); - - it('encodes a 4-byte address', () => { - expect( - encode( - new Uint8Array([1, 2, 3, 4]), 68 - ) - ).toEqual('as7QnGMf'); - }); - - it('enodes a 8-byte address', () => { - expect( - encode( - new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0]), 68 - ) - ).toEqual('4q7qY5RBG7Z4wv'); - }); -}); diff --git a/packages/keyring/src/address/encode.ts b/packages/keyring/src/address/encode.ts deleted file mode 100644 index 37ed47567f..0000000000 --- a/packages/keyring/src/address/encode.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Prefix } from './types'; - -// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34 - -import bs58 from 'bs58'; -import { assert, u8aConcat, u8aToBuffer, u8aToU8a } from '@plugnet/util'; - -import defaults from './defaults'; -import sshash from './sshash'; - -export default function encode (_key: Uint8Array | string, prefix: Prefix = defaults.prefix): string { - const key = u8aToU8a(_key); - - assert(defaults.allowedDecodedLengths.includes(key.length), `Expected a valid key to convert, with length ${defaults.allowedDecodedLengths}`); - - const isPublicKey = key.length === 32; - - const input = u8aConcat(new Uint8Array([prefix]), key); - const hash = sshash(input); - - return bs58.encode( - u8aToBuffer( - u8aConcat(input, hash.subarray(0, isPublicKey ? 2 : 1)) - ) - ); -} diff --git a/packages/keyring/src/address/index.ts b/packages/keyring/src/address/index.ts deleted file mode 100644 index 5197a7169c..0000000000 --- a/packages/keyring/src/address/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import decodeAddress from './decode'; -import encodeAddress from './encode'; -import setAddressPrefix from './setPrefix'; - -export { - decodeAddress, - encodeAddress, - setAddressPrefix -}; diff --git a/packages/keyring/src/address/setPrefix.spec.ts b/packages/keyring/src/address/setPrefix.spec.ts deleted file mode 100644 index 8e915f2feb..0000000000 --- a/packages/keyring/src/address/setPrefix.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import encode from './encode'; -import setPrefix from './setPrefix'; - -describe('setPrefix', () => { - beforeEach(() => { - setPrefix(68); - }); - - it('sets and allows encoding using', () => { - expect( - encode( - new Uint8Array([1]) - ) - ).toEqual('PqtB'); - }); -}); diff --git a/packages/keyring/src/address/setPrefix.ts b/packages/keyring/src/address/setPrefix.ts deleted file mode 100644 index a2d9c71351..0000000000 --- a/packages/keyring/src/address/setPrefix.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Prefix } from './types'; - -import defaults from './defaults'; - -export default function setPrefix (prefix: Prefix): void { - defaults.prefix = prefix; -} diff --git a/packages/keyring/src/address/sshash.ts b/packages/keyring/src/address/sshash.ts deleted file mode 100644 index 1003d6f2b5..0000000000 --- a/packages/keyring/src/address/sshash.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a, u8aConcat } from '@plugnet/util'; -import { blake2AsU8a } from '@plugnet/util-crypto'; - -const SS58_PREFIX = stringToU8a('SS58PRE'); - -export default function hash (key: Uint8Array): Uint8Array { - return blake2AsU8a(u8aConcat(SS58_PREFIX, key), 512); -} diff --git a/packages/keyring/src/address/types.ts b/packages/keyring/src/address/types.ts deleted file mode 100644 index 02aaf6165f..0000000000 --- a/packages/keyring/src/address/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export type Prefix = 0 | 1 | 3 | 42 | 43 | 68 | 69; diff --git a/packages/keyring/src/defaults.ts b/packages/keyring/src/defaults.ts deleted file mode 100644 index d6044488bc..0000000000 --- a/packages/keyring/src/defaults.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// default substrate dev phrase -const DEV_PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk'; - -// seed from the above phrase -const DEV_SEED = '0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e'; - -export { - DEV_PHRASE, - DEV_SEED -}; diff --git a/packages/keyring/src/index.spec.ts b/packages/keyring/src/index.spec.ts deleted file mode 100644 index 63bd4dbcbd..0000000000 --- a/packages/keyring/src/index.spec.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a, stringToU8a } from '@plugnet/util'; -import { cryptoWaitReady } from '@plugnet/util-crypto'; - -import Keyring from '.'; -import setPrefix from './address/setPrefix'; - -describe('keypair', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - describe('ed25519', () => { - const publicKeyOne = new Uint8Array([47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238]); - const publicKeyTwo = new Uint8Array([215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26]); - const seedOne = stringToU8a('12345678901234567890123456789012'); - const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'); - let keypair: Keyring; - - beforeEach(async () => { - keypair = new Keyring({ type: 'ed25519' }); - - keypair.addFromSeed(seedOne, {}); - }); - - it('adds the pair', () => { - expect( - keypair.addFromSeed(seedTwo, {}).publicKey() - ).toEqual(publicKeyTwo); - }); - - it('creates a ed25519 pair via mnemonicToSeed', () => { - expect( - keypair.addFromUri( - 'seed sock milk update focus rotate barely fade car face mechanic mercy' - ).address() - ).toEqual('5DkQP32jP4DVJLWWBRBoZF2tpWjqFrcrTBo6H5NcSk7MxKCC'); - }); - - it('adds from a mnemonic', () => { - setPrefix(68); - - expect( - keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address() - ).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH'); - }); - - it('allows publicKeys retrieval', () => { - keypair.addFromSeed(seedTwo, {}); - - expect( - keypair.getPublicKeys() - ).toEqual([ publicKeyOne, publicKeyTwo ]); - }); - - it('allows retrieval of a specific item', () => { - expect( - keypair.getPair(publicKeyOne).publicKey() - ).toEqual(publicKeyOne); - }); - - it('allows adding from JSON', () => { - expect( - keypair.addFromJson( - JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') - ).publicKey() - ).toEqual( - new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79]) - ); - }); - - it('signs and verifies', () => { - const MESSAGE = stringToU8a('this is a message'); - const pair = keypair.getPair(publicKeyOne); - const signature = pair.sign(MESSAGE); - - expect(pair.verify(MESSAGE, signature)).toBe(true); - }); - }); - - describe('sr25519', () => { - const publicKeyOne = new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99]); - const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f'); - const seedOne = stringToU8a('12345678901234567890123456789012'); - const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'); - let keypair: Keyring; - - beforeEach(() => { - keypair = new Keyring({ type: 'sr25519' }); - - keypair.addFromSeed(seedOne, {}); - }); - - it('creates with dev phrase when only path specified', () => { - expect( - keypair.createFromUri('//Alice').address() - ).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); - }); - - it('adds the pair', () => { - expect( - keypair.addFromSeed(seedTwo, {}).publicKey() - ).toEqual(publicKeyTwo); - }); - - it('adds from a mnemonic', () => { - setPrefix(68); - - expect( - keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address() - ).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ'); - }); - - it('allows publicKeys retrieval', () => { - keypair.addFromSeed(seedTwo, {}); - - expect( - keypair.getPublicKeys() - ).toEqual([ publicKeyOne, publicKeyTwo ]); - }); - - it('allows retrieval of a specific item', () => { - expect( - keypair.getPair(publicKeyOne).publicKey() - ).toEqual(publicKeyOne); - }); - - it('allows adding from JSON', () => { - expect( - keypair.addFromJson( - JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') - ).publicKey() - ).toEqual( - new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79]) - ); - }); - - it('signs and verifies', () => { - const MESSAGE = stringToU8a('this is a message'); - const pair = keypair.getPair(publicKeyOne); - const signature = pair.sign(MESSAGE); - - expect(pair.verify(MESSAGE, signature)).toBe(true); - }); - }); -}); diff --git a/packages/keyring/src/index.ts b/packages/keyring/src/index.ts deleted file mode 100644 index 45a0de8b70..0000000000 --- a/packages/keyring/src/index.ts +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeypairType } from '@plugnet/util-crypto/types'; -import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions } from './types'; - -import { assert, assertSingletonPackage, hexToU8a, isNumber, isHex, stringToU8a } from '@plugnet/util'; -import { keyExtractSuri, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret, keyFromPath } from '@plugnet/util-crypto'; - -import { decodeAddress, encodeAddress, setAddressPrefix } from './address'; -import { DEV_PHRASE } from './defaults'; -import createPair from './pair'; -import Pairs from './pairs'; - -assertSingletonPackage('@plugnet/keyring'); - -/** - * # @plugnet/keyring - * - * ## Overview - * - * @name Keyring - * @summary Keyring management of user accounts - * @description Allows generation of keyring pairs from a variety of input combinations, such as - * json object containing account address or public key, account metadata, and account encoded using - * `addFromJson`, or by providing those values as arguments separately to `addFromAddress`, - * or by providing the mnemonic (seed phrase) and account metadata as arguments to `addFromMnemonic`. - * Stores the keyring pairs in a keyring pair dictionary. Removal of the keyring pairs from the keyring pair - * dictionary is achieved using `removePair`. Retrieval of all the stored pairs via `getPairs` or perform - * lookup of a pair for a given account address or public key using `getPair`. JSON metadata associated with - * an account may be obtained using `toJson` accompanied by the account passphrase. - */ -export default class Keyring implements KeyringInstance { - private _pairs: Pairs; - private _type: KeypairType; - - constructor (options: KeyringOptions = {}) { - options.type = options.type || 'ed25519'; - - assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`); - - this._pairs = new Pairs(); - this._type = options.type; - - setAddressPrefix(isNumber(options.addressPrefix) ? options.addressPrefix : 42); - } - - decodeAddress = decodeAddress; - encodeAddress = encodeAddress; - setAddressPrefix = setAddressPrefix; - - /** - * @description retrieve the pairs (alias for getPairs) - */ - get pairs (): Array { - return this.getPairs(); - } - - /** - * @description retrieve the publicKeys (alias for getPiblicKeys) - */ - get publicKeys (): Array { - return this.getPublicKeys(); - } - - /** - * @description Returns the type of the keyring, either ed25519 of sr25519 - */ - get type (): KeypairType { - return this._type; - } - - /** - * @name addPair - * @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary - */ - addPair (pair: KeyringPair): KeyringPair { - return this._pairs.add(pair); - } - - /** - * @name addFromAddress - * @summary Stores an account, given an account address, as a Key/Value (public key, pair) in Keyring Pair Dictionary - * @description Allows user to explicitely provide separate inputs including account address or public key, and optionally - * the associated account metadata, and the default encoded value as arguments (that may be obtained from the json file - * of an account backup), and then generates a keyring pair from them that it passes to - * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. - */ - addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair { - const publicKey = this.decodeAddress(address, ignoreChecksum); - - return this.addPair(createPair(type, { publicKey }, meta, encoded)); - } - - /** - * @name addFromJson - * @summary Stores an account, given JSON data, as a Key/Value (public key, pair) in Keyring Pair Dictionary - * @description Allows user to provide a json object argument that contains account information (that may be obtained from the json file - * of an account backup), and then generates a keyring pair from it that it passes to - * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. - */ - addFromJson ({ address, encoded, encoding: { content, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair { - const type = version === '0' || !Array.isArray(content) - ? this.type - : content[1]; - - return this.addFromAddress(address, meta, hexToU8a(encoded), type, ignoreChecksum); - } - - /** - * @name addFromMnemonic - * @summary Stores an account, given a mnemonic, as a Key/Value (public key, pair) in Keyring Pair Dictionary - * @description Allows user to provide a mnemonic (seed phrase that is provided when account is originally created) - * argument and a metadata argument that contains account information (that may be obtained from the json file - * of an account backup), and then generates a keyring pair from it that it passes to - * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. - */ - addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { - return this.addFromUri(mnemonic, meta, type); - } - - /** - * @name addFromSeed - * @summary Stores an account, given seed data, as a Key/Value (public key, pair) in Keyring Pair Dictionary - * @description Stores in a keyring pair dictionary the public key of the pair as a key and the pair as the associated value. - * Allows user to provide the account seed as an argument, and then generates a keyring pair from it that it passes to - * `addPair` to store in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. - */ - addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { - const keypair = type === 'sr25519' - ? schnorrkelFromSeed(seed) - : naclFromSeed(seed); - - return this.addPair(createPair(type, keypair, meta, null)); - } - - /** - * @name addFromUri - * @summary Creates an account via an suri - * @description Extracts the phrase, path and password from a SURI format for specifying secret keys `//////` (the `///password` may be omitted, and `/` and `//` maybe repeated and mixed). The secret can be a hex string, mnemonic phrase or a string (to be padded) - */ - addFromUri (suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { - return this.addPair( - this.createFromUri(suri, meta, type) - ); - } - - /** - * @name createFromUri - * @summry Creates a Keypair from an suri - * @description This creates a pair from the suri, but does not add it to the keyring - */ - createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { - // here we only aut-add the dev phrase if we have a hard-derived path - const suri = _suri.indexOf('//') === 0 - ? `${DEV_PHRASE}${_suri}` - : _suri; - const { password, phrase, path } = keyExtractSuri(suri); - let seed; - - if (isHex(phrase, 256)) { - seed = hexToU8a(phrase); - } else { - const str = phrase as string; - const parts = str.split(' '); - - if ([12, 15, 18, 21, 24].includes(parts.length)) { - // FIXME This keeps compat with older versions, but breaks compat with subkey - // seed = type === 'sr25519' - // ? mnemonicToMiniSecret(phrase, password) - // : mnemonicToSeed(phrase, password); - seed = mnemonicToMiniSecret(phrase, password); - } else { - assert(str.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes'); - - seed = stringToU8a(str.padEnd(32)); - } - } - - const keypair = type === 'sr25519' - ? schnorrkelFromSeed(seed) - : naclFromSeed(seed); - const derived = keyFromPath(keypair, path, type); - - return createPair(type, derived, meta, null); - } - - /** - * @name getPair - * @summary Retrieves an account keyring pair from the Keyring Pair Dictionary, given an account address - * @description Returns a keyring pair value from the keyring pair dictionary by performing - * a key lookup using the provided account address or public key (after decoding it). - */ - getPair (address: string | Uint8Array): KeyringPair { - return this._pairs.get(address); - } - - /** - * @name getPairs - * @summary Retrieves all account keyring pairs from the Keyring Pair Dictionary - * @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary. - */ - getPairs (): Array { - return this._pairs.all(); - } - - /** - * @name getPublicKeys - * @summary Retrieves Public Keys of all Keyring Pairs stored in the Keyring Pair Dictionary - * @description Returns an array list of all the public keys associated with each of the keyring pair values that are stored in the keyring pair dictionary. - */ - getPublicKeys (): Array { - return this._pairs - .all() - .map(({ publicKey }) => - publicKey() - ); - } - - /** - * @name removePair - * @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary. - */ - removePair (address: string | Uint8Array): void { - this._pairs.remove(address); - } - - /** - * @name toJson - * @summary Returns a JSON object associated with the input argument that contains metadata assocated with an account - * @description Returns a JSON object containing the metadata associated with an account - * when valid address or public key and when the account passphrase is provided if the account secret - * is not already unlocked and available in memory. Note that in [Polkadot-JS Apps](https://github.com/polkadot-js/apps) the user - * may backup their account to a JSON file that contains this information. - */ - toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json { - return this._pairs.get(address).toJson(passphrase); - } -} - -export { Keyring, decodeAddress, encodeAddress, setAddressPrefix }; diff --git a/packages/keyring/src/pair/decode.spec.ts b/packages/keyring/src/pair/decode.spec.ts deleted file mode 100644 index 43b18bca1a..0000000000 --- a/packages/keyring/src/pair/decode.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import testingPairs from '../testingPairs'; - -const keyring = testingPairs({ type: 'ed25519' }, false); - -describe('decode', () => { - it('fails when no data provided', () => { - expect( - () => keyring.alice.decodePkcs8() - ).toThrow(/No encrypted data available/); - }); - - it('returns correct publicKey from encoded', () => { - const PASS = 'testing'; - - expect( - () => keyring.alice.decodePkcs8( - PASS, keyring.alice.encodePkcs8(PASS) - ) - ).not.toThrow(); - }); -}); diff --git a/packages/keyring/src/pair/decode.ts b/packages/keyring/src/pair/decode.ts deleted file mode 100644 index 6378d14c24..0000000000 --- a/packages/keyring/src/pair/decode.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assert, stringToU8a, u8aFixLength } from '@plugnet/util'; -import { naclDecrypt } from '@plugnet/util-crypto'; -import { PairInfo } from './types'; - -import { NONCE_LENGTH, PKCS8_DIVIDER, PKCS8_HEADER, PUB_LENGTH, SEC_LENGTH, SEED_LENGTH } from './defaults'; - -const SEED_OFFSET = PKCS8_HEADER.length; - -type DecodeResult = PairInfo & { - secretKey: Uint8Array -}; - -export default function decode (passphrase?: string, _encrypted?: Uint8Array | null): DecodeResult { - assert(_encrypted, `No encrypted data available to decode`); - - const encrypted = (_encrypted as Uint8Array); - const encoded = passphrase - ? (naclDecrypt( - encrypted.subarray(NONCE_LENGTH), - encrypted.subarray(0, NONCE_LENGTH), - u8aFixLength(stringToU8a(passphrase), 256, true) - ) as Uint8Array) - : encrypted; - - assert(encoded, `Unable to unencrypt using the supplied passphrase`); - - const header = encoded.subarray(0, PKCS8_HEADER.length); - - assert(header.toString() === PKCS8_HEADER.toString(), 'Invalid Pkcs8 header found in body'); - - let secretKey = encoded.subarray(SEED_OFFSET, SEED_OFFSET + SEC_LENGTH); - let divOffset = SEED_OFFSET + SEC_LENGTH; - let divider = encoded.subarray(divOffset, divOffset + PKCS8_DIVIDER.length); - - // old-style, we have the seed here - if (divider.toString() !== PKCS8_DIVIDER.toString()) { - divOffset = SEED_OFFSET + SEED_LENGTH; - secretKey = encoded.subarray(SEED_OFFSET, divOffset); - divider = encoded.subarray(divOffset, divOffset + PKCS8_DIVIDER.length); - } - - assert(divider.toString() === PKCS8_DIVIDER.toString(), 'Invalid Pkcs8 divider found in body'); - - const pubOffset = divOffset + PKCS8_DIVIDER.length; - const publicKey = encoded.subarray(pubOffset, pubOffset + PUB_LENGTH); - - return { - publicKey, - secretKey - }; -} diff --git a/packages/keyring/src/pair/defaults.ts b/packages/keyring/src/pair/defaults.ts deleted file mode 100644 index 1be12dc166..0000000000 --- a/packages/keyring/src/pair/defaults.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -const NONCE_LENGTH = 24; -const PKCS8_DIVIDER = new Uint8Array([161, 35, 3, 33, 0]); -const PKCS8_HEADER = new Uint8Array([48, 83, 2, 1, 1, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32]); -const PUB_LENGTH = 32; -const SEC_LENGTH = 64; -const SEED_LENGTH = 32; - -export { - NONCE_LENGTH, - PKCS8_DIVIDER, - PKCS8_HEADER, - PUB_LENGTH, - SEC_LENGTH, - SEED_LENGTH -}; diff --git a/packages/keyring/src/pair/encode.spec.ts b/packages/keyring/src/pair/encode.spec.ts deleted file mode 100644 index 7e9befc6a6..0000000000 --- a/packages/keyring/src/pair/encode.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import testingPairs from '../testingPairs'; -import { PKCS8_DIVIDER, PKCS8_HEADER, PUB_LENGTH, SEC_LENGTH } from './defaults'; - -const PKCS8_LENGTH = PKCS8_DIVIDER.length + PKCS8_HEADER.length + PUB_LENGTH + SEC_LENGTH; -const ENCODED_LENGTH = 157; - -const keyring = testingPairs({ type: 'ed25519' }, false); - -describe('encode', () => { - it('returns PKCS8 when no passphrase supplied', () => { - expect( - keyring.alice.encodePkcs8() - ).toHaveLength(PKCS8_LENGTH); - }); - - it('returns encoded PKCS8 when passphrase supplied', () => { - expect( - keyring.alice.encodePkcs8('testing') - ).toHaveLength(ENCODED_LENGTH); - }); -}); diff --git a/packages/keyring/src/pair/encode.ts b/packages/keyring/src/pair/encode.ts deleted file mode 100644 index e73a4afe8b..0000000000 --- a/packages/keyring/src/pair/encode.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { PairInfo } from './types'; - -import { stringToU8a, u8aConcat, u8aFixLength, assert } from '@plugnet/util'; -import { naclEncrypt } from '@plugnet/util-crypto'; - -import { PKCS8_DIVIDER, PKCS8_HEADER } from './defaults'; - -export default function encode ({ publicKey, secretKey }: PairInfo, passphrase?: string): Uint8Array { - assert(secretKey, 'Expected a valid secretKey to be passed to encode'); - - const encoded = u8aConcat( - PKCS8_HEADER, - secretKey as Uint8Array, - PKCS8_DIVIDER, - publicKey - ); - - if (!passphrase) { - return encoded; - } - - const { encrypted, nonce } = naclEncrypt(encoded, u8aFixLength(stringToU8a(passphrase), 256, true)); - - return u8aConcat(nonce, encrypted); -} diff --git a/packages/keyring/src/pair/index.spec.ts b/packages/keyring/src/pair/index.spec.ts deleted file mode 100644 index cdf2f0d6c3..0000000000 --- a/packages/keyring/src/pair/index.spec.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import testingPairs from '../testingPairs'; - -const keyring = testingPairs({ type: 'ed25519' }, false); - -describe('pair', () => { - const SIGNATURE = new Uint8Array([80, 191, 198, 147, 225, 207, 75, 88, 126, 39, 129, 109, 191, 38, 72, 181, 75, 254, 81, 143, 244, 79, 237, 38, 236, 141, 28, 252, 134, 26, 169, 234, 79, 33, 153, 158, 151, 34, 175, 188, 235, 20, 35, 135, 83, 120, 139, 211, 233, 130, 1, 208, 201, 215, 73, 80, 56, 98, 185, 196, 11, 8, 193, 14]); - - it('has a publicKey', () => { - expect( - keyring.alice.publicKey() - ).toEqual( - new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79]) - ); - }); - - it('allows signing', () => { - expect( - keyring.alice.sign( - new Uint8Array([0x61, 0x62, 0x63, 0x64]) - ) - ).toEqual(SIGNATURE); - }); - - it('validates a correctly signed message', () => { - expect( - keyring.alice.verify( - new Uint8Array([0x61, 0x62, 0x63, 0x64]), - SIGNATURE - ) - ).toEqual(true); - }); - - it('fails a correctly signed message (message changed)', () => { - expect( - keyring.alice.verify( - new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]), - SIGNATURE - ) - ).toEqual(false); - }); - - it('allows setting/getting of meta', () => { - keyring.bob.setMeta({ foo: 'bar', something: 'else' }); - - expect(keyring.bob.getMeta()).toMatchObject({ foo: 'bar', something: 'else' }); - - keyring.bob.setMeta({ something: 'thing' }); - - expect(keyring.bob.getMeta()).toMatchObject({ foo: 'bar', something: 'thing' }); - }); -}); diff --git a/packages/keyring/src/pair/index.ts b/packages/keyring/src/pair/index.ts deleted file mode 100644 index 1c58460d05..0000000000 --- a/packages/keyring/src/pair/index.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair, KeypairType } from '@plugnet/util-crypto/types'; -import { KeyringPair, KeyringPair$Json, KeyringPair$Meta } from '../types'; -import { PairInfo } from './types'; - -import { naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@plugnet/util-crypto'; - -import { encodeAddress } from '../address'; -import decode from './decode'; -import encode from './encode'; -import toJson from './toJson'; - -const isSr25519 = (type: KeypairType): boolean => - type === 'sr25519'; - -const fromSeed = (type: KeypairType, seed: Uint8Array) => - isSr25519(type) - ? schnorrkelFromSeed(seed) - : naclFromSeed(seed); - -const sign = (type: KeypairType, message: Uint8Array, pair: Partial) => - isSr25519(type) - ? schnorrkelSign(message, pair) - : naclSign(message, pair); - -const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array) => - isSr25519(type) - ? schnorrkelVerify(message, signature, publicKey) - : naclVerify(message, signature, publicKey); - -/** - * @name pair - * @summary Creates a keyring pair object - * @description Creates a keyring pair object with provided account public key, metadata, and encoded arguments. - * The keyring pair stores the account state including the encoded address and associated metadata. - * - * It has properties whose values are functions that may be called to perform account actions: - * - * - `address` function retrieves the address associated with the account. - * - `decodedPkcs8` function is called with the account passphrase and account encoded public key. - * It decodes the encoded public key using the passphrase provided to obtain the decoded account public key - * and associated secret key that are then available in memory, and changes the account address stored in the - * state of the pair to correspond to the address of the decoded public key. - * - `encodePkcs8` function when provided with the correct passphrase associated with the account pair - * and when the secret key is in memory (when the account pair is not locked) it returns an encoded - * public key of the account. - * - `getMeta` returns the metadata that is stored in the state of the pair, either when it was originally - * created or set via `setMeta`. - * - `publicKey` returns the public key stored in memory for the pair. - * - `sign` may be used to return a signature by signing a provided message with the secret - * key (if it is in memory) using Nacl. - * - `toJson` calls another `toJson` function and provides the state of the pair, - * it generates arguments to be passed to the other `toJson` function including an encoded public key of the account - * that it generates using the secret key from memory (if it has been made available in memory) - * and the optionally provided passphrase argument. It passes a third boolean argument to `toJson` - * indicating whether the public key has been encoded or not (if a passphrase argument was provided then it is encoded). - * The `toJson` function that it calls returns a JSON object with properties including the `address` - * and `meta` that are assigned with the values stored in the corresponding state variables of the account pair, - * an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding` - * property that indicates whether the public key value of the `encoded` property is encoded or not. - */ -export default function createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair { - return { - type, - address: (): string => - encodeAddress(publicKey), - decodePkcs8: (passphrase?: string, _encoded?: Uint8Array | null): void => { - const decoded = decode(passphrase, _encoded || encoded); - - if (decoded.secretKey.length === 64) { - publicKey = decoded.publicKey; - secretKey = decoded.secretKey; - } else { - const pair = fromSeed(type, decoded.secretKey); - - publicKey = pair.publicKey; - secretKey = pair.secretKey; - } - }, - encodePkcs8: (passphrase?: string): Uint8Array => - encode({ publicKey, secretKey }, passphrase), - getMeta: (): KeyringPair$Meta => - meta, - isLocked: (): boolean => - (!secretKey || secretKey.length === 0), - lock: (): void => { - secretKey = new Uint8Array(0); - }, - publicKey: (): Uint8Array => - publicKey, - setMeta: (additional: KeyringPair$Meta): void => { - meta = { ...meta, ...additional }; - }, - sign: (message: Uint8Array): Uint8Array => - sign(type, message, { publicKey, secretKey }), - toJson: (passphrase?: string): KeyringPair$Json => - toJson(type, { meta, publicKey }, encode({ publicKey, secretKey }, passphrase), !!passphrase), - verify: (message: Uint8Array, signature: Uint8Array): boolean => - verify(type, message, signature, publicKey) - }; -} diff --git a/packages/keyring/src/pair/nobody.ts b/packages/keyring/src/pair/nobody.ts deleted file mode 100644 index 85e77e75d1..0000000000 --- a/packages/keyring/src/pair/nobody.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeyringPair, KeyringPair$Json, KeyringPair$Meta } from '../types'; - -import addressEncode from '../address/encode'; - -const publicKey = new Uint8Array(32); -const address = addressEncode(publicKey); -const meta = { - isTesting: true, - name: 'nobody' -}; -const json: KeyringPair$Json = { - address, - encoded: '', - encoding: { - content: ['pkcs8', 'ed25519'], - type: 'none', - version: '0' - }, - meta -}; - -export default function everybody (): KeyringPair { - return { - type: 'ed25519', - address: (): string => - address, - decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void => - undefined, - encodePkcs8: (passphrase?: string): Uint8Array => - new Uint8Array(0), - getMeta: (): KeyringPair$Meta => - meta, - isLocked: (): boolean => - true, - lock: (): void => { - // no locking, it is always locked - }, - publicKey: (): Uint8Array => - publicKey, - setMeta: (meta: KeyringPair$Meta): void => - undefined, - sign: (message: Uint8Array): Uint8Array => - new Uint8Array(64), - toJson: (passphrase?: string): KeyringPair$Json => - json, - verify: (message: Uint8Array, signature: Uint8Array): boolean => - false - }; -} diff --git a/packages/keyring/src/pair/toJson.spec.ts b/packages/keyring/src/pair/toJson.spec.ts deleted file mode 100644 index 022055ec6b..0000000000 --- a/packages/keyring/src/pair/toJson.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import testingPairs from '../testingPairs'; - -const keyring = testingPairs({ type: 'ed25519' }, false); - -describe('toJson', () => { - it('creates an unencoded output with no passphrase', () => { - expect( - keyring.alice.toJson() - ).toMatchObject({ - address: '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua', - encoded: '0x3053020101300506032b657004220420416c696365202020202020202020202020202020202020202020202020202020d172a74cda4c865912c32ba0a80a57ae69abae410e5ccb59dee84e2f4432db4fa123032100d172a74cda4c865912c32ba0a80a57ae69abae410e5ccb59dee84e2f4432db4f', - encoding: { - content: ['pkcs8', 'ed25519'], - type: 'none', - version: '2' - }, - meta: { - name: 'alice', - isTesting: true - } - }); - }); - - it('creates an encoded output with passphrase', () => { - const json = keyring.alice.toJson('testing'); - - expect(json.encoded).toHaveLength(316); - expect(json).toMatchObject({ - address: '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua', - encoding: { - content: ['pkcs8', 'ed25519'], - type: 'xsalsa20-poly1305', - version: '2' - } - }); - }); -}); diff --git a/packages/keyring/src/pair/toJson.ts b/packages/keyring/src/pair/toJson.ts deleted file mode 100644 index 0037168e32..0000000000 --- a/packages/keyring/src/pair/toJson.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeypairType } from '@plugnet/util-crypto/types'; -import { KeyringPair$Json, KeyringPair$Meta } from '../types'; - -import { u8aToHex } from '@plugnet/util'; - -import { encodeAddress } from '../address'; - -type PairStateJson = KeyringPair$Meta & { - publicKey: Uint8Array -}; - -export default function toJson (type: KeypairType, { publicKey, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json { - return { - address: encodeAddress(publicKey), - encoded: u8aToHex(encoded), - encoding: { - content: ['pkcs8', type], - type: isEncrypted - ? 'xsalsa20-poly1305' - : 'none', - version: '2' - }, - meta - }; -} diff --git a/packages/keyring/src/pair/types.ts b/packages/keyring/src/pair/types.ts deleted file mode 100644 index 23dee4b6fc..0000000000 --- a/packages/keyring/src/pair/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export type PairInfo = { - publicKey: Uint8Array, - secretKey?: Uint8Array, - seed?: Uint8Array | null -}; diff --git a/packages/keyring/src/pairs.ts b/packages/keyring/src/pairs.ts deleted file mode 100644 index 408ef3b50b..0000000000 --- a/packages/keyring/src/pairs.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeyringPairs, KeyringPair } from './types'; - -import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@plugnet/util'; - -import addressDecode from './address/decode'; - -type KeyringPairMap = { - // @ts-ignore we use coercion :( - [index: Uint8Array]: KeyringPair -}; - -export default class Pairs implements KeyringPairs { - private _map: KeyringPairMap; - - constructor () { - this._map = {}; - } - - add (pair: KeyringPair): KeyringPair { - // @ts-ignore we use coercion :( - this._map[pair.publicKey()] = pair; - - return pair; - } - - all (): Array { - return Object.values(this._map); - } - - get (address: string | Uint8Array): KeyringPair { - // @ts-ignore we use coercion :( - const pair = this._map[addressDecode(address)]; - - assert(pair, () => { - const formatted: string = isU8a(address) || isHex(address) - ? u8aToHex(u8aToU8a(address)) - : address; - - return `Unable to retrieve keypair '${formatted}'`; - }); - - return pair; - } - - remove (address: string | Uint8Array): void { - // @ts-ignore we use coercion :( - delete this._map[addressDecode(address)]; - } -} diff --git a/packages/keyring/src/suri.spec.ts b/packages/keyring/src/suri.spec.ts deleted file mode 100644 index b056745542..0000000000 --- a/packages/keyring/src/suri.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// From https://github.com/paritytech/substrate/wiki/Secret-URI-Test-Vectors - -import { u8aToHex } from '@plugnet/util'; -import { cryptoWaitReady } from '@plugnet/util-crypto'; - -import Keyring from '.'; - -const PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk'; - -const TESTS = [ - { - pk: '0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a', - ss: '5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV', - uri: PHRASE - }, - { - pk: '0xb69355deefa7a8f33e9297f5af22e680f03597a99d4f4b1c44be47e7a2275802', - ss: '5GC6LfpV352HtJPySfAecb5JdePtf4R9Vq49NUU8RhzgBqgq', - uri: `${PHRASE}///password` - }, - { - pk: '0x40b9675df90efa6069ff623b0fdfcf706cd47ca7452a5056c7ad58194d23440a', - ss: '5DXZzrDxHbkQov4QBAY4TjpwnHCMrKXkomTnKSw8UArBEY5v', - uri: `${PHRASE}/foo` - }, - { - pk: '0x547d4a55642ec7ebadc0bd29b6e570b8c926059b3c0655d4948075e9a7e6f31e', - ss: '5DyV6fZuvPemWrUqBgWwTSgoV86w6xms3KhkFU6cQcWxU8eP', - uri: `${PHRASE}//foo` - }, - { - pk: '0x3841947ffcde6f5fef26fb68b59bb8665637e30e32ec2051f99cf6b9c674fe09', - ss: '5DLU27is5iViNopQb2KxsTyPx6j4vCu8X3sk3j3NNLkPCqKM', - uri: `${PHRASE}//foo/bar` - }, - { - pk: '0xdc142f7476a7b0aa262aeccf207f1d18daa90762db393006741e8a31f39dbc53', - ss: '5H3GPTqDSpjkfDwbHy12PD6BWm8jvGSX4xYC8UMprHpTPcRg', - uri: `${PHRASE}/foo//bar` - }, - { - pk: '0xa2e56b06407a6d1e819d2fc33fa0ec604b29c2e868b70b3696bb049b8725934b', - ss: '5FkHmNgbg64MwStgCyDi2Uw3ufFu11mqQgmWT9uwK4Lghvpv', - uri: `${PHRASE}//foo/bar//42/69` - }, - { - pk: '0x0e0d24e3e1ff2c07f269c99e2e0df8681fda1851ac42fc846ca2daaa90cd8f14', - ss: '5CP8S23JBNXYNpJsL7ESPJBNnUZE6itcfM4EnDxEhaVEU6dT', - uri: `${PHRASE}//foo/bar//42/69///password` - }, - { - pk: '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d', - ss: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', - uri: `${PHRASE}//Alice` - } -]; - -describe('keyring.addFromUri', () => { - const keyring = new Keyring({ type: 'sr25519' }); - - beforeEach(async () => { - await cryptoWaitReady(); - }); - - TESTS.forEach(({ pk, ss, uri }) => { - it(`creates ${uri}`, () => { - const pair = keyring.addFromUri(uri); - - expect(u8aToHex(pair.publicKey())).toEqual(pk); - expect(pair.address()).toEqual(ss); - }); - }); -}); diff --git a/packages/keyring/src/testing.ts b/packages/keyring/src/testing.ts deleted file mode 100644 index ca5dd7791f..0000000000 --- a/packages/keyring/src/testing.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeyringInstance, KeyringOptions } from './types'; - -import { hexToU8a } from '@plugnet/util'; - -import createPair from './pair'; -import Keyring from '.'; - -// As per substrate -const SEEDS = ['Alice', 'Alice//stash', 'Bob', 'Charlie', 'Dave', 'Eve', 'Ferdie']; -// NOTE This is not great, but a testing keyring is for testing - what happens is that in most cases -// the keyring is initialises before anythign else. Since the sr25519 crypto is async, this creates -// problems with adding the keys -const PAIRS = [ - [ - hexToU8a('0x98319d4ff8a9508c4bb0cf0b5a78d760a0b2082c02775e6e82370816fedfff48925a225d97aa00682d6a59b95b18780c10d7032336e88f3442b42361f4a66011'), - hexToU8a('0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d') - ], - [ - hexToU8a('0xe8da6c9d810e020f5e3c7f5af2dea314cbeaa0d72bc6421e92c0808a0c584a6046ab28e97c3ffc77fe12b5a4d37e8cd4afbfebbf2391ffc7cb07c0f38c023efd'), - hexToU8a('0xbe5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f') - ], - [ - hexToU8a('0x081ff694633e255136bdb456c20a5fc8fed21f8b964c11bb17ff534ce80ebd5941ae88f85d0c1bfc37be41c904e1dfc01de8c8067b0d6d5df25dd1ac0894a325'), - hexToU8a('0x8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48') - ], - [ - hexToU8a('0xa8f2d83016052e5d6d77b2f6fd5d59418922a09024cda701b3c34369ec43a7668faf12ff39cd4e5d92bb773972f41a7a5279ebc2ed92264bed8f47d344f8f18c'), - hexToU8a('0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22') - ], - [ - hexToU8a('0x20e05482ca4677e0edbc58ae9a3a59f6ed3b1a9484ba17e64d6fe8688b2b7b5d108c4487b9323b98b11fe36cb301b084e920f7b7895536809a6d62a451b25568'), - hexToU8a('0x306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20') - ], - [ - hexToU8a('0x683576abfd5dc35273e4264c23095a1bf21c14517bece57c7f0cc5c0ed4ce06a3dbf386b7828f348abe15d76973a72009e6ef86a5c91db2990cb36bb657c6587'), - hexToU8a('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e') - ], - [ - hexToU8a('0xb835c20f450079cf4f513900ae9faf8df06ad86c681884122c752a4b2bf74d4303e4f21bc6cc62bb4eeed5a9cce642c25e2d2ac1464093b50f6196d78e3a7426'), - hexToU8a('0x1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c') - ] -]; - -/** - * @name testKeyring - * @summary Create an instance of Keyring pre-populated with locked test accounts - * @description The test accounts (i.e. alice, bob, dave, eve, ferdie) - * are available on the dev chain and each test account is initialised with DOT funds. - */ -export default function testKeyring (options: KeyringOptions = {}, isDerived: boolean = true): KeyringInstance { - const keyring = new Keyring(options); - - SEEDS.forEach((entry, index) => { - const meta = { - isTesting: true, - name: entry.replace('//', '_').toLowerCase() - }; - const pair = !isDerived - ? keyring.addFromUri(entry, meta, options.type) - : keyring.addPair( - createPair('sr25519', { publicKey: PAIRS[index][1], secretKey: PAIRS[index][0] }, meta) - ); - - pair.lock = () => { - // we don't have lock/unlock functionality here - }; - }); - - return keyring; -} diff --git a/packages/keyring/src/testingPairs.spec.ts b/packages/keyring/src/testingPairs.spec.ts deleted file mode 100644 index e386456c78..0000000000 --- a/packages/keyring/src/testingPairs.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { cryptoWaitReady } from '@plugnet/util-crypto'; - -import testingPairs from './testingPairs'; - -describe('testingPairs', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - it('creates without failing', () => { - expect( - Object.keys(testingPairs()) - ).toHaveLength(1 + 7); - }); - - it('has the correct address for Alice (non-HDKD)', () => { - expect( - testingPairs({ type: 'ed25519' }, false).alice.address() - ).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'); - }); - - it('has the correct address for Alice (HDKD)', () => { - expect( - testingPairs({ type: 'ed25519' }, true).alice.address() - ).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); - }); -}); diff --git a/packages/keyring/src/testingPairs.ts b/packages/keyring/src/testingPairs.ts deleted file mode 100644 index a5c20b0979..0000000000 --- a/packages/keyring/src/testingPairs.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeyringPair, KeyringOptions } from './types'; - -import createKeyring from './testing'; -import nobody from './pair/nobody'; - -type TestKeyringMap = { - [index: string]: KeyringPair -}; - -export default function testKeyringPairs (options?: KeyringOptions, isDerived: boolean = true): TestKeyringMap { - const keyring = createKeyring(options, isDerived); - const pairs = keyring.getPairs(); - - return pairs.reduce((result, pair) => { - const { name } = pair.getMeta(); - - result[name as string] = pair; - - return result; - }, { 'nobody': nobody() } as TestKeyringMap); -} diff --git a/packages/keyring/src/types.ts b/packages/keyring/src/types.ts deleted file mode 100644 index 96480db3c0..0000000000 --- a/packages/keyring/src/types.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2017-2019 @polkadot/keyring authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeypairType } from '@plugnet/util-crypto/types'; -import { Prefix } from './address/types'; - -export type KeyringOptions = { - addressPrefix?: Prefix, - type?: KeypairType -}; - -export type KeyringPair$Meta = { - [index: string]: any -}; - -export type KeyringPair$JsonVersion = '0' | '1' | '2'; - -export type KeyringPair$JsonEncoding = { - content: ['pkcs8', KeypairType], - type: 'xsalsa20-poly1305' | 'none', - version: KeyringPair$JsonVersion -}; - -export type KeyringPair$Json = { - address: string, - encoded: string, - encoding: KeyringPair$JsonEncoding, - meta: KeyringPair$Meta -}; - -export interface KeyringPair { - readonly type: KeypairType; - - address: () => string; - decodePkcs8: (passphrase?: string, encoded?: Uint8Array) => void; - encodePkcs8: (passphrase?: string) => Uint8Array; - getMeta: () => KeyringPair$Meta; - isLocked: () => boolean; - lock: () => void; - publicKey: () => Uint8Array; - setMeta: (meta: KeyringPair$Meta) => void; - sign (message: Uint8Array): Uint8Array; - toJson (passphrase?: string): KeyringPair$Json; - verify (message: Uint8Array, signature: Uint8Array): boolean; -} - -export interface KeyringPairs { - add: (pair: KeyringPair) => KeyringPair; - all: () => Array; - get: (address: string | Uint8Array) => KeyringPair; - remove: (address: string | Uint8Array) => void; -} - -export interface KeyringInstance { - readonly pairs: Array; - readonly publicKeys: Array; - readonly type: KeypairType; - - decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array; - encodeAddress (key: Uint8Array | string): string; - setAddressPrefix (prefix: Prefix): void; - - addPair (pair: KeyringPair): KeyringPair; - addFromAddress (address: string | Uint8Array, meta?: KeyringPair$Meta, encoded?: Uint8Array | null, type?: KeypairType, ignoreChecksum?: boolean): KeyringPair; - addFromJson (pair: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair; - addFromMnemonic (mnemonic: string, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; - addFromSeed (seed: Uint8Array, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; - addFromUri (suri: string, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; - createFromUri (suri: string, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; - getPair (address: string | Uint8Array): KeyringPair; - getPairs (): Array; - getPublicKeys (): Array; - removePair (address: string | Uint8Array): void; - toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json; -} diff --git a/packages/rpc-core/README.md b/packages/rpc-core/README.md index 3747fe7ad4..222f39674f 100644 --- a/packages/rpc-core/README.md +++ b/packages/rpc-core/README.md @@ -1,4 +1,4 @@ -# @polkadot/rpc-core +# @plugnet/rpc-core This library provides a clean wrapper around all the methods exposed by a Polkadot network client. diff --git a/packages/rpc-core/package.json b/packages/rpc-core/package.json index ae4f943583..7ef7e4511f 100644 --- a/packages/rpc-core/package.json +++ b/packages/rpc-core/package.json @@ -33,6 +33,6 @@ "@plugnet/jsonrpc": "^0.76.1", "@plugnet/rpc-provider": "^0.76.1", "@plugnet/types": "^0.76.1", - "@plugnet/util": "^0.76.1" + "@plugnet/util": "^0.76.2-beta.0" } } diff --git a/packages/rpc-core/test/e2e/basics.test.js b/packages/rpc-core/test/e2e/basics.test.js index 7b82880d51..17810cbcf6 100644 --- a/packages/rpc-core/test/e2e/basics.test.js +++ b/packages/rpc-core/test/e2e/basics.test.js @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Ws from '@polkadot/rpc-provider/ws'; +import Ws from '@plugnet/rpc-provider/ws'; import Rpc from '../../src'; diff --git a/packages/rpc-core/test/e2e/chain.test.js b/packages/rpc-core/test/e2e/chain.test.js index a40d734b18..c6f04ba340 100644 --- a/packages/rpc-core/test/e2e/chain.test.js +++ b/packages/rpc-core/test/e2e/chain.test.js @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Ws from '@polkadot/rpc-provider/ws'; +import Ws from '@plugnet/rpc-provider/ws'; import Rpc from '../../src'; diff --git a/packages/rpc-core/test/e2e/krummelanke.test.js b/packages/rpc-core/test/e2e/krummelanke.test.js index 6e48ad1182..d095bb9134 100644 --- a/packages/rpc-core/test/e2e/krummelanke.test.js +++ b/packages/rpc-core/test/e2e/krummelanke.test.js @@ -2,8 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import storage from '@polkadot/storage'; -import Ws from '@polkadot/rpc-provider/ws'; +import storage from '@plugnet/storage'; +import Ws from '@plugnet/rpc-provider/ws'; import Rpc from '../../src'; diff --git a/packages/rpc-core/test/e2e/state.test.js b/packages/rpc-core/test/e2e/state.test.js index 4699540c3e..3759474c88 100644 --- a/packages/rpc-core/test/e2e/state.test.js +++ b/packages/rpc-core/test/e2e/state.test.js @@ -2,8 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Ws from '@polkadot/rpc-provider/ws'; -import storage from '@polkadot/storage/static'; +import Ws from '@plugnet/rpc-provider/ws'; +import storage from '@plugnet/storage/static'; import Rpc from '../../src'; diff --git a/packages/rpc-core/test/e2e/subscribe.test.js b/packages/rpc-core/test/e2e/subscribe.test.js index da1da3d374..5d16b507b3 100644 --- a/packages/rpc-core/test/e2e/subscribe.test.js +++ b/packages/rpc-core/test/e2e/subscribe.test.js @@ -2,8 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Ws from '@polkadot/rpc-provider/ws'; -import storage from '@polkadot/storage/static'; +import Ws from '@plugnet/rpc-provider/ws'; +import storage from '@plugnet/storage/static'; import Rpc from '../../src'; diff --git a/packages/rpc-provider/package.json b/packages/rpc-provider/package.json index bfc4d7f9ab..a2d799beab 100644 --- a/packages/rpc-provider/package.json +++ b/packages/rpc-provider/package.json @@ -30,10 +30,10 @@ "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme", "dependencies": { "@babel/runtime": "^7.4.3", - "@plugnet/keyring": "^0.76.1", + "@plugnet/keyring": "^0.76.2-beta.0", "@plugnet/storage": "^0.76.1", - "@plugnet/util": "^0.76.1", - "@plugnet/util-crypto": "^0.76.1", + "@plugnet/util": "^0.76.2-beta.0", + "@plugnet/util-crypto": "^0.76.2-beta.0", "@types/nock": "^9.3.1", "eventemitter3": "^3.1.0", "isomorphic-fetch": "^2.2.1", diff --git a/packages/rpc-rx/README.md b/packages/rpc-rx/README.md index 23ed7c4d4c..e7e09be0fe 100644 --- a/packages/rpc-rx/README.md +++ b/packages/rpc-rx/README.md @@ -1,6 +1,6 @@ -# @polkadot/rpc-rx +# @plugnet/rpc-rx -An RxJs wrapper around the [@polkadot/rpc-core](../rpc-core). +An RxJs wrapper around the [@plugnet/rpc-core](../rpc-core). ## Classes diff --git a/packages/rpc-rx/src/cached.spec.ts b/packages/rpc-rx/src/cached.spec.ts index 1cc8402623..1739dd243a 100644 --- a/packages/rpc-rx/src/cached.spec.ts +++ b/packages/rpc-rx/src/cached.spec.ts @@ -7,7 +7,7 @@ import testingPairs from '@plugnet/keyring/testingPairs'; import { RpcInterface$Section } from '@plugnet/rpc-core/types'; import { AccountId } from '@plugnet/types'; -jest.mock('@polkadot/rpc-provider/ws', () => class { +jest.mock('@plugnet/rpc-provider/ws', () => class { isConnected = () => true; on = () => true; send = () => true; diff --git a/packages/rpc-rx/src/index.spec.ts b/packages/rpc-rx/src/index.spec.ts index e2fe6eedee..450b926bf9 100644 --- a/packages/rpc-rx/src/index.spec.ts +++ b/packages/rpc-rx/src/index.spec.ts @@ -4,7 +4,7 @@ import { isFunction } from '@plugnet/util'; -jest.mock('@polkadot/rpc-provider/ws', () => class { +jest.mock('@plugnet/rpc-provider/ws', () => class { isConnected = () => true; on = () => true; send = () => true; diff --git a/packages/rpc-rx/src/replay.spec.ts b/packages/rpc-rx/src/replay.spec.ts index 5a43027096..f993aefeef 100644 --- a/packages/rpc-rx/src/replay.spec.ts +++ b/packages/rpc-rx/src/replay.spec.ts @@ -5,7 +5,7 @@ import { Observable } from 'rxjs'; import { RpcInterface$Section } from '@plugnet/rpc-core/types'; -jest.mock('@polkadot/rpc-provider/ws', () => class { +jest.mock('@plugnet/rpc-provider/ws', () => class { isConnected = () => true; on = () => true; send = () => true; diff --git a/packages/rpc-rx/test/e2e/subscribe.test.js b/packages/rpc-rx/test/e2e/subscribe.test.js index abb0a8fdb5..689fcc359f 100644 --- a/packages/rpc-rx/test/e2e/subscribe.test.js +++ b/packages/rpc-rx/test/e2e/subscribe.test.js @@ -2,8 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Ws from '@polkadot/rpc-provider/ws'; -import storage from '@polkadot/storage/static'; +import Ws from '@plugnet/rpc-provider/ws'; +import storage from '@plugnet/storage/static'; import RpcRx from '../../src'; diff --git a/packages/type-extrinsics/package.json b/packages/type-extrinsics/package.json index a6519f118b..42bbf53ae8 100644 --- a/packages/type-extrinsics/package.json +++ b/packages/type-extrinsics/package.json @@ -12,6 +12,6 @@ "dependencies": { "@babel/runtime": "^7.4.3", "@plugnet/types": "^0.76.1", - "@plugnet/util": "^0.76.1" + "@plugnet/util": "^0.76.2-beta.0" } } diff --git a/packages/type-extrinsics/test/e2e/transfer.spec.js b/packages/type-extrinsics/test/e2e/transfer.spec.js index ccc456f208..8a9f04ee1f 100644 --- a/packages/type-extrinsics/test/e2e/transfer.spec.js +++ b/packages/type-extrinsics/test/e2e/transfer.spec.js @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Rpc from '@polkadot/rpc-core'; -import Ws from '@polkadot/rpc-provider/ws'; -import testingPairs from '@polkadot/keyring/testingPairs'; +import Rpc from '@plugnet/rpc-core'; +import Ws from '@plugnet/rpc-provider/ws'; +import testingPairs from '@plugnet/keyring/testingPairs'; import extrinsics from '../../src/static'; diff --git a/packages/type-storage/package.json b/packages/type-storage/package.json index d6a09598ac..ddc65fd65e 100644 --- a/packages/type-storage/package.json +++ b/packages/type-storage/package.json @@ -30,9 +30,9 @@ "homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-storage#readme", "dependencies": { "@babel/runtime": "^7.4.3", - "@plugnet/keyring": "^0.76.1", + "@plugnet/keyring": "^0.76.2-beta.0", "@plugnet/types": "^0.76.1", - "@plugnet/util": "^0.76.1", - "@plugnet/util-crypto": "^0.76.1" + "@plugnet/util": "^0.76.2-beta.0", + "@plugnet/util-crypto": "^0.76.2-beta.0" } } diff --git a/packages/types/package.json b/packages/types/package.json index be593034cc..21680d0707 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -30,7 +30,7 @@ "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme", "dependencies": { "@babel/runtime": "^7.4.3", - "@plugnet/keyring": "^0.76.1", - "@plugnet/util": "^0.76.1" + "@plugnet/keyring": "^0.76.2-beta.0", + "@plugnet/util": "^0.76.2-beta.0" } } diff --git a/packages/types/src/scripts/MetadataMdWrapper.js b/packages/types/src/scripts/MetadataMdWrapper.js index 9e97124d17..4240c49f9c 100644 --- a/packages/types/src/scripts/MetadataMdWrapper.js +++ b/packages/types/src/scripts/MetadataMdWrapper.js @@ -8,7 +8,7 @@ require('@babel/register')({ plugins: [ ['module-resolver', { alias: { - '^@polkadot/types(.*)': './packages/types/src\\2' + '^@plugnet/types(.*)': './packages/types/src\\2' } }] ] diff --git a/packages/util-crypto/LICENSE b/packages/util-crypto/LICENSE deleted file mode 100644 index 0d381b2e97..0000000000 --- a/packages/util-crypto/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -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. diff --git a/packages/util-crypto/README.md b/packages/util-crypto/README.md deleted file mode 100644 index 90f60cc6f6..0000000000 --- a/packages/util-crypto/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# @polkadot/util-crypto - -Various useful cyrpto utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. - -## Usage - -Installation - - -``` -yarn add @polkadot/util-crypto -``` - -Functions can be imported as follows: - -```js -import { mnemonicGenerate } from '@polkadot/util-crypto'; -``` - -## Utilities - -[Utilities](SUMMARY.md) diff --git a/packages/util-crypto/package.json b/packages/util-crypto/package.json deleted file mode 100644 index 65c157f471..0000000000 --- a/packages/util-crypto/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "@plugnet/util-crypto", - "version": "0.76.1", - "description": "A collection of useful crypto utilities for @plugnet", - "main": "index.js", - "keywords": [ - "Plugnet" - ], - "author": "Jaco Greeff ", - "maintainers": [ - "Jaco Greeff " - ], - "contributors": [], - "license": "Apache-2.0", - "engines": { - "node": ">=6.4" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/polkadot-js/common.git" - }, - "bugs": { - "url": "https://github.com/polkadot-js/common/issues" - }, - "homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme", - "dependencies": { - "@babel/runtime": "^7.4.3", - "@plugnet/util": "^0.76.1", - "@polkadot/wasm-crypto": "^0.8.1", - "@types/bip39": "^2.4.2", - "@types/pbkdf2": "^3.0.0", - "@types/secp256k1": "^3.5.0", - "@types/webassembly-js-api": "^0.0.2", - "@types/xxhashjs": "^0.2.1", - "bip39": "^2.5.0", - "blakejs": "^1.1.0", - "js-sha3": "^0.8.0", - "secp256k1": "^3.6.2", - "tweetnacl": "^1.0.1", - "xxhashjs": "^0.2.2" - } -} diff --git a/packages/util-crypto/src/blake2/asHex.spec.ts b/packages/util-crypto/src/blake2/asHex.spec.ts deleted file mode 100644 index 32f586ef2a..0000000000 --- a/packages/util-crypto/src/blake2/asHex.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { blake2AsHex } from '.'; - -describe('blake2AsHex', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a 64-bit value (specified)', () => { - expect( - blake2AsHex('abc', 64) - ).toEqual('0xd8bb14d833d59559'); - }); - - it('returns a 128-bit value (as specified)', () => { - expect( - blake2AsHex('abc', 128) - ).toEqual('0xcf4ab791c62b8d2b2109c90275287816'); - }); - - it('returns a 256-bit value (default)', () => { - expect( - blake2AsHex('abc') - ).toEqual('0xbddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319'); - }); - - it('returns a 512-bit value (as specified)', () => { - expect( - blake2AsHex('abc', 512) - ).toEqual('0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923'); - }); - - it('matches with the Rust implementation', () => { - expect( - blake2AsHex( - hexToU8a('0x454545454545454545454545454545454545454545454545454545454545454501000000000000002481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29dbdbf025dd4a69a6f4ee6e1577b251b655097e298b692cb34c18d3182cac3de0dc00000000'), 256 - ) - ).toEqual('0x1025e5db74fdaf4d2818822dccf0e1604ae9ccc62f26cecfde23448ff0248abf'); - }); -}); diff --git a/packages/util-crypto/src/blake2/asHex.ts b/packages/util-crypto/src/blake2/asHex.ts deleted file mode 100644 index 3886999ca5..0000000000 --- a/packages/util-crypto/src/blake2/asHex.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import blake2AsU8a from './asU8a'; - -/** - * @name blake2AsHex - * @summary Creates a blake2b hex from the input. - * @description - * From a `Uint8Array` input, create the blake2b and return the result as a hex string with the specified `bitLength`. - * @example - *
- * - * ```javascript - * import { blake2AsHex } from '@plugnet/util-crypto'; - * - * blake2AsHex('abc'); // => 0xba80a53f981c4d0d - * ``` - */ -export default function blake2AsHex (data: Uint8Array | string, bitLength: number = 256): string { - return u8aToHex( - blake2AsU8a(data, bitLength) - ); -} diff --git a/packages/util-crypto/src/blake2/asU8a.spec.ts b/packages/util-crypto/src/blake2/asU8a.spec.ts deleted file mode 100644 index 32035eec4b..0000000000 --- a/packages/util-crypto/src/blake2/asU8a.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { blake2AsU8a } from '.'; - -describe('blake2AsU8a', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a 64-bit value by default', () => { - expect( - blake2AsU8a('abc') - ).toEqual( - new Uint8Array([189, 221, 129, 60, 99, 66, 57, 114, 49, 113, 239, 63, 238, 152, 87, 155, 148, 150, 78, 59, 177, 203, 62, 66, 114, 98, 200, 192, 104, 213, 35, 25]) - ); - }); - - it('returns a 128-bit value (as specified)', () => { - expect( - blake2AsU8a('abc', 128) - ).toEqual( - new Uint8Array([207, 74, 183, 145, 198, 43, 141, 43, 33, 9, 201, 2, 117, 40, 120, 22]) - ); - }); - - it('returns a 256-bit value (as specified)', () => { - expect( - blake2AsU8a('abc', 256) - ).toEqual( - new Uint8Array([189, 221, 129, 60, 99, 66, 57, 114, 49, 113, 239, 63, 238, 152, 87, 155, 148, 150, 78, 59, 177, 203, 62, 66, 114, 98, 200, 192, 104, 213, 35, 25]) - ); - }); - - it('returns a 512-bit value (as specified)', () => { - expect( - blake2AsU8a('abc', 512) - ).toEqual( - hexToU8a('0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923') - ); - }); -}); diff --git a/packages/util-crypto/src/blake2/asU8a.ts b/packages/util-crypto/src/blake2/asU8a.ts deleted file mode 100644 index edb7612014..0000000000 --- a/packages/util-crypto/src/blake2/asU8a.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import blakejs from 'blakejs'; -import { u8aToU8a } from '@plugnet/util'; -import { blake2b, isReady } from '@plugnet/wasm-crypto'; - -/** - * @name blake2AsU8a - * @summary Creates a blake2b u8a from the input. - * @description - * From a `Uint8Array` input, create the blake2b and return the result as a u8a with the specified `bitLength`. - * @example - *
- * - * ```javascript - * import { blake2AsU8a } from '@plugnet/util-crypto'; - * - * blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d] - * ``` - */ -export default function blake2AsU8a (data: Uint8Array | string, bitLength: number = 256, key: Uint8Array | null = null): Uint8Array { - const byteLength = Math.ceil(bitLength / 8); - - return isReady() - ? blake2b(u8aToU8a(data), u8aToU8a(key), byteLength) - : blakejs.blake2b(data, key, byteLength); -} diff --git a/packages/util-crypto/src/blake2/index.ts b/packages/util-crypto/src/blake2/index.ts deleted file mode 100644 index 00c34fb9c7..0000000000 --- a/packages/util-crypto/src/blake2/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Create blake2b values with specified bitlengths - */ - -export { default as blake2AsHex } from './asHex'; -export { default as blake2AsU8a } from './asU8a'; diff --git a/packages/util-crypto/src/index.ts b/packages/util-crypto/src/index.ts deleted file mode 100644 index 5c7d8b6e14..0000000000 --- a/packages/util-crypto/src/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import './polyfill'; - -import wasmCrypto from '@plugnet/wasm-crypto'; - -export * from './blake2'; -export * from './keccak'; -export * from './key'; -export * from './mnemonic'; -export * from './nacl'; -export * from './random'; -export * from './schnorrkel'; -export * from './secp256k1'; -export * from './sha512'; -export * from './xxhash'; - -export function cryptoWaitReady (): Promise { - return wasmCrypto - .waitReady() - .then(() => true) - .catch((error) => { - console.error('Unable to initialize @polkadot/util-crypto', error); - - return false; - }); -} - -// start init process immediately -cryptoWaitReady().catch(() => { - // shouldn't happen, logged above -}); diff --git a/packages/util-crypto/src/keccak/asHex.spec.ts b/packages/util-crypto/src/keccak/asHex.spec.ts deleted file mode 100644 index 9f3ecb2288..0000000000 --- a/packages/util-crypto/src/keccak/asHex.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { waitReady } from '@plugnet/wasm-crypto'; - -import { keccakAsHex } from '.'; - -const value = 'test value'; -const result = '2d07364b5c231c56ce63d49430e085ea3033c750688ba532b24029124c26ca5e'; - -describe('keccakAsHex', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a prefixed hex representation', () => { - expect( - keccakAsHex(value) - ).toEqual(`0x${result}`); - }); -}); diff --git a/packages/util-crypto/src/keccak/asHex.ts b/packages/util-crypto/src/keccak/asHex.ts deleted file mode 100644 index 0389945e5c..0000000000 --- a/packages/util-crypto/src/keccak/asHex.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import keccakAsU8a from './asU8a'; - -/** - * @name keccakAsHex - * @summary Creates a keccak hex string from the input. - * @description - * From either a `string` or a `Buffer` input, create the keccak and return the result as a `0x` prefixed hex string. - * @example - *
- * - * ```javascript - * import { keccakAsHex } from '@plugnet/util-crypto'; - * - * keccakAsHex('123'); // => 0x... - * ``` - */ -export default function keccakAsHex (value: Buffer | Uint8Array | string): string { - return u8aToHex( - keccakAsU8a(value) - ); -} diff --git a/packages/util-crypto/src/keccak/asU8a.spec.ts b/packages/util-crypto/src/keccak/asU8a.spec.ts deleted file mode 100644 index 90f8410309..0000000000 --- a/packages/util-crypto/src/keccak/asU8a.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a, stringToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { keccakAsU8a } from '.'; - -describe('keccakAsU8a', () => { - beforeEach(async () => { - await waitReady(); - }); - - const input = 'test value'; - const output = hexToU8a( - '0x2d07364b5c231c56ce63d49430e085ea3033c750688ba532b24029124c26ca5e' - ); - - it('returns an hex representation (string)', () => { - expect( - keccakAsU8a(input) - ).toEqual(output); - }); - - it('returns an hex representation (Buffer)', () => { - expect( - keccakAsU8a( - Buffer.from(input) - ) - ).toEqual(output); - }); - - it('returns an hex representation (Uint8Array)', () => { - expect( - keccakAsU8a( - stringToU8a(input) - ) - ).toEqual(output); - }); -}); diff --git a/packages/util-crypto/src/keccak/asU8a.ts b/packages/util-crypto/src/keccak/asU8a.ts deleted file mode 100644 index 600dd849d4..0000000000 --- a/packages/util-crypto/src/keccak/asU8a.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import jssha3 from 'js-sha3'; -import { u8aToU8a } from '@plugnet/util'; -import { isReady, keccak256 } from '@plugnet/wasm-crypto'; - -/** - * @name keccakAsU8a - * @summary Creates a keccak Uint8Array from the input. - * @description - * From either a `string` or a `Buffer` input, create the keccak and return the result as a `Uint8Array`. - * @example - *
- * - * ```javascript - * import { keccakAsU8a } from '@plugnet/util-crypto'; - * - * keccakAsU8a('123'); // => Uint8Array - * ``` - */ -export default function keccakAsU8a (value: Buffer | Uint8Array | string): Uint8Array { - return isReady() - ? keccak256(u8aToU8a(value)) - : new Uint8Array( - jssha3.keccak256.update(value).arrayBuffer() - ); -} diff --git a/packages/util-crypto/src/keccak/index.ts b/packages/util-crypto/src/keccak/index.ts deleted file mode 100644 index 33e4f25a8e..0000000000 --- a/packages/util-crypto/src/keccak/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Create Keccak256 values as hex & Uint8Array output - */ - -export { default as keccakAsHex } from './asHex'; -export { default as keccakAsU8a } from './asU8a'; diff --git a/packages/util-crypto/src/key/DeriveJunction.ts b/packages/util-crypto/src/key/DeriveJunction.ts deleted file mode 100644 index 998fc9ede9..0000000000 --- a/packages/util-crypto/src/key/DeriveJunction.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; -import { bnToHex, compactAddLength, hexToU8a, isBn, isHex, isNumber, isString, stringToU8a } from '@plugnet/util'; - -import blake2AsU8a from '../blake2/asU8a'; - -const RE_NUMBER = /^\d+$/; - -const JUNCTION_ID_LEN: number = 32; -const BN_OPTIONS = { - bitLength: 256, - isLe: true -}; - -export default class DeriveJunction { - private _chainCode: Uint8Array = new Uint8Array(32); - private _isHard: boolean = false; - - static from (value: string): DeriveJunction { - const [code, isHard] = value[0] === '/' - ? [value.substr(1), true] - : [value, false]; - const result = new DeriveJunction(); - - result.soft( - RE_NUMBER.test(code) - ? parseInt(code, 10) - : code - ); - - return isHard - ? result.harden() - : result; - } - - get chainCode (): Uint8Array { - return this._chainCode; - } - - get isHard (): boolean { - return this._isHard; - } - - get isSoft (): boolean { - return !this._isHard; - } - - hard (value: number | BN | string | Uint8Array): DeriveJunction { - return this.soft(value).harden(); - } - - harden (): DeriveJunction { - this._isHard = true; - - return this; - } - - soft (value: number | BN | string | Uint8Array): DeriveJunction { - if (isNumber(value) || isBn(value)) { - return this.soft(bnToHex(value, BN_OPTIONS)); - } else if (isString(value)) { - return isHex(value) - ? this.soft(hexToU8a(value)) - : this.soft(compactAddLength(stringToU8a(value))); - } - - if (value.length > JUNCTION_ID_LEN) { - return this.soft(blake2AsU8a(value)); - } - - this._chainCode.fill(0); - this._chainCode.set(value, 0); - - return this; - } - - soften (): DeriveJunction { - this._isHard = false; - - return this; - } -} diff --git a/packages/util-crypto/src/key/extractPath.spec.ts b/packages/util-crypto/src/key/extractPath.spec.ts deleted file mode 100644 index 3ab5c187f7..0000000000 --- a/packages/util-crypto/src/key/extractPath.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import keyExtractPath from './extractPath'; - -describe('keyExtractPath', () => { - it('extracts properly from soft', () => { - expect( - keyExtractPath('/1') - ).toEqual({ - parts: ['/1'], - path: [ - { _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ] - }); - }); - - it('extracts properly from hard', () => { - expect( - keyExtractPath('//1') - ).toEqual({ - parts: ['//1'], - path: [ - { _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ] - }); - }); - - it('extracts properly from hard/soft', () => { - expect( - keyExtractPath('//1/2') - ).toEqual({ - parts: ['//1', '/2'], - path: [ - { _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }, - { _isHard: false, _chainCode: Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ] - }); - }); - - it('does not extract from invalid paths', () => { - expect( - () => keyExtractPath('1/2') - ).toThrow(/does not match input/); - }); - - it('does not extract from invalid paths', () => { - expect( - () => keyExtractPath('hello') - ).toThrow(/does not match input/); - }); -}); diff --git a/packages/util-crypto/src/key/extractPath.ts b/packages/util-crypto/src/key/extractPath.ts deleted file mode 100644 index f2578ffbce..0000000000 --- a/packages/util-crypto/src/key/extractPath.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import DeriveJunction from './DeriveJunction'; -import { assert } from '@plugnet/util'; - -const RE_JUNCTION = /\/(\/?)([^\/]+)/g; - -type ExtractResult = { - parts: null | Array, - path: Array -}; - -/** - * @description Extract derivation juntions from the supplied path - */ -export default function keyExtractPath (derivePath: string): ExtractResult { - const parts = derivePath.match(RE_JUNCTION); - const path: Array = []; - let constructed = ''; - - if (parts) { - constructed = parts.join(''); - - parts.forEach((value: string) => { - path.push(DeriveJunction.from(value.substr(1))); - }); - } - - assert(constructed === derivePath, `Re-constructed path "${constructed}" does not match input`); - - return { - parts, - path - }; -} diff --git a/packages/util-crypto/src/key/extractSuri.spec.ts b/packages/util-crypto/src/key/extractSuri.spec.ts deleted file mode 100644 index 509f059dd1..0000000000 --- a/packages/util-crypto/src/key/extractSuri.spec.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import keyExtractSuri from './extractSuri'; - -describe('keyExtractSuri', () => { - it('does not extract from invalid suri', () => { - expect( - () => keyExtractSuri('//2') - ).toThrow(/to a secret URI/); - }); - - it('derives on "hello world"', () => { - expect( - keyExtractSuri('hello world') - ).toEqual({ - path: [], - phrase: 'hello world' - }); - }); - - it('derives on "hello world/1', () => { - expect( - keyExtractSuri('hello world/1') - ).toEqual({ - path: [ - { _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world/DOT', () => { - expect( - keyExtractSuri('hello world/DOT') - ).toEqual({ - path: [ - { _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world//1', () => { - expect( - keyExtractSuri('hello world//1') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world//DOT', () => { - expect( - keyExtractSuri('hello world//DOT') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world//1/DOT', () => { - expect( - keyExtractSuri('hello world//1/DOT') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }, - { _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world//DOT/1', () => { - expect( - keyExtractSuri('hello world//DOT/1') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }, - { _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'hello world' - }); - }); - - it('derives on "hello world///password"', () => { - expect( - keyExtractSuri('hello world///password') - ).toEqual({ - password: 'password', - path: [], - phrase: 'hello world' - }); - }); - - it('derives on "hello world//1/DOT///password"', () => { - expect( - keyExtractSuri('hello world//1/DOT///password') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }, - { _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - password: 'password', - phrase: 'hello world' - }); - }); - - it('derives on "hello world/1//DOT///password"', () => { - expect( - keyExtractSuri('hello world/1//DOT///password') - ).toEqual({ - path: [ - { _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }, - { _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - password: 'password', - phrase: 'hello world' - }); - }); - - it('derives on actual Alice', () => { - expect( - keyExtractSuri('bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice') - ).toEqual({ - path: [ - { _isHard: true, _chainCode: Uint8Array.from([20, 65, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - ], - phrase: 'bottom drive obey lake curtain smoke basket hold race lonely fit walk' - }); - }); -}); diff --git a/packages/util-crypto/src/key/extractSuri.ts b/packages/util-crypto/src/key/extractSuri.ts deleted file mode 100644 index 2f9279cb77..0000000000 --- a/packages/util-crypto/src/key/extractSuri.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assert, isNull } from '@plugnet/util'; - -import DeriveJunction from './DeriveJunction'; -import keyExtractPath from './extractPath'; - -type ExtractResult = { - password?: string, - path: Array, - phrase: string -}; - -const RE_CAPTURE = /^(\w+( \w+)*)((\/\/?[^\/]+)*)(\/\/\/(.*))?$/; - -/** - * @description Extracts the phrase, path and password from a SURI format for specifying secret keys `//////` (the `///password` may be omitted, and `/` and `//` maybe repeated and mixed). - */ -export default function keyExtract (suri: string): ExtractResult { - const matches = suri.match(RE_CAPTURE); - - assert(!isNull(matches), `Unable to match '${suri}' to a secret URI`); - - const [, phrase, , derivePath, , , password] = matches as Array; - const { path } = keyExtractPath(derivePath); - - return { - password, - path, - phrase - }; -} diff --git a/packages/util-crypto/src/key/fromPath.ts b/packages/util-crypto/src/key/fromPath.ts deleted file mode 100644 index 5aca2ba49e..0000000000 --- a/packages/util-crypto/src/key/fromPath.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { KeypairType, Keypair } from '../types'; - -import DeriveJunction from './DeriveJunction'; -import keyHdkdEd15519 from './hdkdEd25519'; -import keyHdkdSr15519 from './hdkdSr25519'; - -export default function keyFromPath (pair: Keypair, path: Array, type: KeypairType): Keypair { - const isEd25519 = type === 'ed25519'; - - return path.reduce((pair, junction) => { - return isEd25519 - ? keyHdkdEd15519(pair, junction) - : keyHdkdSr15519(pair, junction); - }, pair); -} diff --git a/packages/util-crypto/src/key/hdkdEd25519.ts b/packages/util-crypto/src/key/hdkdEd25519.ts deleted file mode 100644 index f010ed4995..0000000000 --- a/packages/util-crypto/src/key/hdkdEd25519.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import { assert } from '@plugnet/util'; - -import naclDeriveHard from '../nacl/deriveHard'; -import naclKeypairFromSeed from '../nacl/keypair/fromSeed'; -import DeriveJunction from './DeriveJunction'; - -export default function keyHdkdEd25519 (keypair: Keypair, { chainCode, isHard }: DeriveJunction): Keypair { - assert(isHard, 'A soft key was found in the path (and is unsupported)'); - - return naclKeypairFromSeed( - naclDeriveHard(keypair.secretKey.subarray(0, 32), chainCode) - ); -} diff --git a/packages/util-crypto/src/key/hdkdSr25519.ts b/packages/util-crypto/src/key/hdkdSr25519.ts deleted file mode 100644 index 59fc664f79..0000000000 --- a/packages/util-crypto/src/key/hdkdSr25519.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import schnorrkelDeriveHard from '../schnorrkel/deriveHard'; -import schnorrkelDeriveSoft from '../schnorrkel/deriveSoft'; -import DeriveJunction from './DeriveJunction'; - -export default function keyHdkdSr25519 (keypair: Keypair, { chainCode, isSoft }: DeriveJunction): Keypair { - return isSoft - ? schnorrkelDeriveSoft(keypair, chainCode) - : schnorrkelDeriveHard(keypair, chainCode); -} diff --git a/packages/util-crypto/src/key/index.ts b/packages/util-crypto/src/key/index.ts deleted file mode 100644 index 9dd50ec3dc..0000000000 --- a/packages/util-crypto/src/key/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Create keys from paths, seeds and password - */ -export { default as keyExtractPath } from './extractPath'; -export { default as keyExtractSuri } from './extractSuri'; -export { default as keyFromPath } from './fromPath'; -export { default as keyHdkdEd25519 } from './hdkdEd25519'; -export { default as keyHdkdSr25519 } from './hdkdEd25519'; diff --git a/packages/util-crypto/src/mnemonic/generate.spec.ts b/packages/util-crypto/src/mnemonic/generate.spec.ts deleted file mode 100644 index 2d95068709..0000000000 --- a/packages/util-crypto/src/mnemonic/generate.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import generate from './generate'; -import validate from './validate'; -import { cryptoWaitReady } from '..'; - -describe('mnemonicGenerate', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - it('generates a valid mnemonic (default strength)', () => { - const mnemonic = generate(); - - console.error(mnemonic); - - expect( - validate(mnemonic) - ).toEqual(true); - }); - - [12, 15, 18, 21, 24].forEach((num) => { - it(`generates a valid mnemonic (${num} words)`, () => { - const mnemonic = generate(num as any); - const isValid = validate(mnemonic); - - console.error(mnemonic); - - expect(mnemonic.split(' ')).toHaveLength(num); - expect(isValid).toEqual(true); - }); - }); -}); diff --git a/packages/util-crypto/src/mnemonic/generate.ts b/packages/util-crypto/src/mnemonic/generate.ts deleted file mode 100644 index f587994101..0000000000 --- a/packages/util-crypto/src/mnemonic/generate.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -import { generateMnemonic } from 'bip39'; -import { bip39Generate, isReady } from '@plugnet/wasm-crypto'; - -type WordCount = 12 | 15 | 18 | 21 | 24; - -// mapping of words to the actual strength (as expected) -const STRENGTH_MAP = { - 12: 16 * 8, - 15: 20 * 8, - 18: 24 * 8, - 21: 28 * 8, - 24: 32 * 8 -}; - -/** - * @name mnemonicGenerate - * @summary Creates a valid mnemonic string using using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). - * @example - *
- * - * ```javascript - * import { mnemonicGenerate } from '@plugnet/util-crypto'; - * - * const mnemonic = mnemonicGenerate(); // => string - * ``` - */ -export default function mnemonicGenerate (numWords: WordCount = 12): string { - return isReady() - ? bip39Generate(numWords) - : generateMnemonic(STRENGTH_MAP[numWords]); -} diff --git a/packages/util-crypto/src/mnemonic/index.ts b/packages/util-crypto/src/mnemonic/index.ts deleted file mode 100644 index 331a8b06e1..0000000000 --- a/packages/util-crypto/src/mnemonic/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -/** - * @summary Create valid mnemonic strings, validate them using BIP39, and convert them to valid seeds - */ - -export { default as mnemonicGenerate } from './generate'; -export { default as mnemonicToEntropy } from './toEntropy'; -export { default as mnemonicToMiniSecret } from './toMiniSecret'; -export { default as mnemonicToSeed } from './toSeed'; -export { default as mnemonicValidate } from './validate'; diff --git a/packages/util-crypto/src/mnemonic/toEntropy.spec.ts b/packages/util-crypto/src/mnemonic/toEntropy.spec.ts deleted file mode 100644 index 37b5c21412..0000000000 --- a/packages/util-crypto/src/mnemonic/toEntropy.spec.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import toEntropy from './toEntropy'; -import tests from '../schnorrkel/keypair/testing'; -import { cryptoWaitReady } from '..'; - -describe('mnemonicToEntropy', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - tests.forEach(([mnemonic, entropy], index) => { - it(`Created correct entropy for ${index}`, () => { - expect(u8aToHex(toEntropy(mnemonic))).toEqual(entropy); - }); - }); -}); diff --git a/packages/util-crypto/src/mnemonic/toEntropy.ts b/packages/util-crypto/src/mnemonic/toEntropy.ts deleted file mode 100644 index 2b337a356e..0000000000 --- a/packages/util-crypto/src/mnemonic/toEntropy.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -import { mnemonicToEntropy } from 'bip39'; -import { hexAddPrefix, hexToU8a } from '@plugnet/util'; -import { bip39ToEntropy, isReady } from '@plugnet/wasm-crypto'; - -export default function toEntropy (mnemonic: string): Uint8Array { - return isReady() - ? bip39ToEntropy(mnemonic) - : hexToU8a( - hexAddPrefix( - mnemonicToEntropy(mnemonic) - ) - ); -} diff --git a/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts b/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts deleted file mode 100644 index dc7d433560..0000000000 --- a/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import mnemonicToMiniSecret from './toMiniSecret'; -import tests from '../schnorrkel/keypair/testing'; -import { cryptoWaitReady } from '..'; - -describe('mnemonicToMiniSecret', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - it('generates a valid seed', () => { - expect( - u8aToHex(mnemonicToMiniSecret('seed sock milk update focus rotate barely fade car face mechanic mercy')) - ).toEqual('0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029'); - }); - - tests.forEach(([mnemonic, , seed], index) => { - it(`Created correct seed for ${index}`, () => { - expect( - u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate')) - ).toEqual( - // mini returned here, only check first 32-bytes (64 hex + 2 prefix) - seed.substr(0, 66) - ); - }); - }); -}); diff --git a/packages/util-crypto/src/mnemonic/toMiniSecret.ts b/packages/util-crypto/src/mnemonic/toMiniSecret.ts deleted file mode 100644 index 8ed0626418..0000000000 --- a/packages/util-crypto/src/mnemonic/toMiniSecret.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -import { pbkdf2Sync } from 'pbkdf2'; -import { bufferToU8a, stringToU8a, u8aToBuffer } from '@plugnet/util'; -import { bip39ToMiniSecret, isReady } from '@plugnet/wasm-crypto'; - -import toEntropy from './toEntropy'; - -export default function toMiniSecret (mnemonic: string, password: string = ''): Uint8Array { - if (isReady()) { - return bip39ToMiniSecret(mnemonic, password); - } - - const entropy = u8aToBuffer(toEntropy(mnemonic)); - const salt = u8aToBuffer(stringToU8a(`mnemonic${password}`)); - - // return the first 32 bytes as the seed - return bufferToU8a( - pbkdf2Sync(entropy, salt, 2048, 64, 'sha512') - ).slice(0, 32); -} diff --git a/packages/util-crypto/src/mnemonic/toSeed.spec.ts b/packages/util-crypto/src/mnemonic/toSeed.spec.ts deleted file mode 100644 index a0f48503a9..0000000000 --- a/packages/util-crypto/src/mnemonic/toSeed.spec.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import toSeed from './toSeed'; - -describe('mnemonicToSeed', () => { - it('generates a valid seed', () => { - expect( - u8aToHex(toSeed('seed sock milk update focus rotate barely fade car face mechanic mercy')) - ).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027'); - }); -}); diff --git a/packages/util-crypto/src/mnemonic/toSeed.ts b/packages/util-crypto/src/mnemonic/toSeed.ts deleted file mode 100644 index b581b06f09..0000000000 --- a/packages/util-crypto/src/mnemonic/toSeed.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { mnemonicToSeed } from 'bip39'; -import { bufferToU8a } from '@plugnet/util'; -import { bip39ToSeed, isReady } from '@plugnet/wasm-crypto'; - -/** - * @name toSeed - * @summary Creates a valid seed from a mnemonic input - * @example - *
- * - * ```javascript - * import { mnemonicGenerate, mnemonicToSeed, mnemonicValidate } from '@plugnet/util-crypto'; - * - * const mnemonic = mnemonicGenerate(); // => string - * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean - * - * if (isValidMnemonic) { - * console.log(`Seed generated from mnemonic: ${mnemonicToSeed(mnemonic)}`); => u8a - * } - * ``` - */ -export default function toSeed (mnemonic: string, password: string = ''): Uint8Array { - return isReady() - ? bip39ToSeed(mnemonic, password) - : bufferToU8a(mnemonicToSeed(mnemonic, password)).subarray(0, 32); -} diff --git a/packages/util-crypto/src/mnemonic/validate.spec.ts b/packages/util-crypto/src/mnemonic/validate.spec.ts deleted file mode 100644 index b9f014b3b0..0000000000 --- a/packages/util-crypto/src/mnemonic/validate.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import validate from './validate'; -import { cryptoWaitReady } from '..'; - -describe('mnemonicValidate', () => { - beforeEach(async () => { - await cryptoWaitReady(); - }); - - it('returns true on valid', () => { - expect( - validate('seed sock milk update focus rotate barely fade car face mechanic mercy') - ).toEqual(true); - }); - - it('returns false on invalid', () => { - expect( - validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit') - ).toEqual(false); - }); -}); diff --git a/packages/util-crypto/src/mnemonic/validate.ts b/packages/util-crypto/src/mnemonic/validate.ts deleted file mode 100644 index 835acd3776..0000000000 --- a/packages/util-crypto/src/mnemonic/validate.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -import { validateMnemonic } from 'bip39'; -import { bip39Validate, isReady } from '@plugnet/wasm-crypto'; - -/** - * @name mnemonicValidate - * @summary Validates a mnemonic input using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). - * @example - *
- * - * ```javascript - * import { mnemonicGenerate, mnemonicValidate } from '@plugnet/util-crypto'; - * - * const mnemonic = mnemonicGenerate(); // => string - * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean - * ``` - */ -export default function mnemonicValidate (mnemonic: string): boolean { - return isReady() - ? bip39Validate(mnemonic) - : validateMnemonic(mnemonic); -} diff --git a/packages/util-crypto/src/nacl/decrypt.spec.ts b/packages/util-crypto/src/nacl/decrypt.spec.ts deleted file mode 100644 index 9289babcf0..0000000000 --- a/packages/util-crypto/src/nacl/decrypt.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { naclDecrypt, naclEncrypt } from '.'; - -describe('naclDecrypt', () => { - it('decrypts a encrypted message', () => { - const secret = new Uint8Array(32); - const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]); - const { encrypted, nonce } = naclEncrypt(message, secret); - - expect( - naclDecrypt(encrypted, nonce, secret) - ).toEqual( - message - ); - }); - - it('returns null on invalid', () => { - expect( - naclDecrypt(new Uint8Array(), new Uint8Array(24), new Uint8Array(32)) - ).toEqual(null); - }); -}); diff --git a/packages/util-crypto/src/nacl/decrypt.ts b/packages/util-crypto/src/nacl/decrypt.ts deleted file mode 100644 index 7cb963ffde..0000000000 --- a/packages/util-crypto/src/nacl/decrypt.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import nacl from 'tweetnacl'; - -/** - * @name naclDecrypt - * @summary Decrypts a message using the supplied secretKey and nonce - * @description - * Returns an decrypted message, using the `secret` and `nonce`. - * @example - *
- * - * ```javascript - * import { naclDecrypt } from '@plugnet/util-crypto'; - * - * naclDecrypt([...], [...], [...]); // => [...] - * ``` - */ -export default function naclDecrypt (encrypted: Uint8Array, nonce: Uint8Array, secret: Uint8Array): Uint8Array | null { - return nacl.secretbox.open(encrypted, nonce, secret) || null; -} diff --git a/packages/util-crypto/src/nacl/deriveHard.ts b/packages/util-crypto/src/nacl/deriveHard.ts deleted file mode 100644 index 164319d567..0000000000 --- a/packages/util-crypto/src/nacl/deriveHard.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { compactAddLength, stringToU8a, u8aConcat } from '@plugnet/util'; - -import blake2AsU8a from '../blake2/asU8a'; - -const HDKD = compactAddLength(stringToU8a('Ed25519HDKD')); - -export default function deriveHard (seed: Uint8Array, chainCode: Uint8Array): Uint8Array { - return blake2AsU8a( - u8aConcat(HDKD, seed, chainCode) - ); -} diff --git a/packages/util-crypto/src/nacl/encrypt.spec.ts b/packages/util-crypto/src/nacl/encrypt.spec.ts deleted file mode 100644 index 2a4b4715fd..0000000000 --- a/packages/util-crypto/src/nacl/encrypt.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { naclEncrypt } from '.'; - -describe('naclEncrypt', () => { - it('encrypts a message', () => { - const secret = new Uint8Array(32); - const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]); - - expect( - naclEncrypt(message, secret, new Uint8Array(24)) - ).toEqual({ - encrypted: new Uint8Array([94, 21, 20, 69, 68, 221, 140, 245, 200, 67, 77, 188, 129, 85, 227, 141, 199, 60, 184, 251, 251, 129, 205, 46, 234]), - nonce: new Uint8Array(24) - }); - }); -}); diff --git a/packages/util-crypto/src/nacl/encrypt.ts b/packages/util-crypto/src/nacl/encrypt.ts deleted file mode 100644 index 2573de1d1c..0000000000 --- a/packages/util-crypto/src/nacl/encrypt.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import nacl from 'tweetnacl'; - -import randomAsU8a from '../random/asU8a'; - -type Encrypted = { - encrypted: Uint8Array, - nonce: Uint8Array -}; - -/** - * @name naclEncrypt - * @summary Encrypts a message using the supplied secretKey and nonce - * @description - * Returns an encrypted message, using the `secretKey` and `nonce`. If the `nonce` was not supplied, a random value is generated. - * @example - *
- * - * ```javascript - * import { naclEncrypt } from '@plugnet/util-crypto'; - * - * naclEncrypt([...], [...]); // => [...] - * ``` - */ -export default function naclEncrypt (message: Uint8Array, secret: Uint8Array, nonce: Uint8Array = randomAsU8a(24)): Encrypted { - return { - encrypted: nacl.secretbox(message, nonce, secret), - nonce - }; -} diff --git a/packages/util-crypto/src/nacl/index.ts b/packages/util-crypto/src/nacl/index.ts deleted file mode 100644 index e246737d34..0000000000 --- a/packages/util-crypto/src/nacl/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Implements [NaCl](http://nacl.cr.yp.to/) secret-key authenticated encryption, public-key authenticated encryption, hashing, and public-key signatures - */ -export { default as naclDecrypt } from './decrypt'; -export { default as deriveHard } from './deriveHard'; -export { default as naclEncrypt } from './encrypt'; -export { default as naclKeypairFromRandom } from './keypair/fromRandom'; -export { default as naclKeypairFromSecret } from './keypair/fromSecret'; -export { default as naclKeypairFromSeed } from './keypair/fromSeed'; -export { default as naclKeypairFromString } from './keypair/fromString'; -export { default as naclSign } from './sign'; -export { default as naclVerify } from './verify'; diff --git a/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts b/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts deleted file mode 100644 index ee020d6b3c..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import { naclKeypairFromRandom } from '..'; - -describe('naclKeypairFromRandom', () => { - let keypair: Keypair; - - beforeEach(() => { - keypair = naclKeypairFromRandom(); - }); - - it('generates a valid publicKey', () => { - expect( - keypair.publicKey - ).toHaveLength(32); - }); - - it('generates a valid secretKey', () => { - expect( - keypair.secretKey - ).toHaveLength(64); - }); -}); diff --git a/packages/util-crypto/src/nacl/keypair/fromRandom.ts b/packages/util-crypto/src/nacl/keypair/fromRandom.ts deleted file mode 100644 index d2b680a9a3..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromRandom.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import nacl from 'tweetnacl'; - -/** - * @name naclKeypairFromRandom - * @summary Creates a new public/secret keypair. - * @description - * Returns a new generate object containing a `publicKey` & `secretKey`. - * @example - *
- * - * ```javascript - * import { naclKeypairFromRandom } from '@plugnet/util-crypto'; - * - * naclKeypairFromRandom(); // => { secretKey: [...], publicKey: [...] } - * ``` - */ -export default function naclKeypairFromRandom (): Keypair { - return nacl.sign.keyPair(); -} diff --git a/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts b/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts deleted file mode 100644 index d2f280fc04..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { naclKeypairFromSecret } from '..'; - -describe('naclKeypairFromSecret', () => { - const secretKey = new Uint8Array([ - 18, 52, 86, 120, 144, 18, 52, 86, - 120, 144, 18, 52, 86, 120, 144, 18, - 18, 52, 86, 120, 144, 18, 52, 86, - 120, 144, 18, 52, 86, 120, 144, 18, - 180, 114, 93, 155, 165, 255, 217, 82, - 16, 250, 209, 11, 193, 10, 88, 218, - 190, 190, 41, 193, 236, 252, 1, 152, - 216, 214, 0, 41, 45, 138, 13, 53 - ]); - - it('generates a valid publicKey/secretKey pair', () => { - expect( - naclKeypairFromSecret(secretKey) - ).toEqual({ - publicKey: new Uint8Array([ - 180, 114, 93, 155, 165, 255, 217, 82, - 16, 250, 209, 11, 193, 10, 88, 218, - 190, 190, 41, 193, 236, 252, 1, 152, - 216, 214, 0, 41, 45, 138, 13, 53 - ]), - secretKey - }); - }); -}); diff --git a/packages/util-crypto/src/nacl/keypair/fromSecret.ts b/packages/util-crypto/src/nacl/keypair/fromSecret.ts deleted file mode 100644 index a410f50c2d..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromSecret.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import nacl from 'tweetnacl'; - -/** - * @name naclKeypairFromSecret - * @summary Creates a new public/secret keypair from a secret. - * @description - * Returns a object containing a `publicKey` & `secretKey` generated from the supplied secret. - * @example - *
- * - * ```javascript - * import { naclKeypairFromSecret } from '@plugnet/util-crypto'; - * - * naclKeypairFromSecret(...); // => { secretKey: [...], publicKey: [...] } - * ``` - */ -export default function naclKeypairFromSecret (secret: Uint8Array): Keypair { - return nacl.sign.keyPair.fromSecretKey(secret); -} diff --git a/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts b/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts deleted file mode 100644 index 46969d9ffe..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { naclKeypairFromSeed } from '..'; - -describe('naclKeypairFromSeed', () => { - // NOTE: Aligned with Rust test, b"12345678901234567890123456789012" - const TEST = stringToU8a('12345678901234567890123456789012'); - const RESULT = { - publicKey: new Uint8Array([ - 0x2f, 0x8c, 0x61, 0x29, 0xd8, 0x16, 0xcf, 0x51, - 0xc3, 0x74, 0xbc, 0x7f, 0x08, 0xc3, 0xe6, 0x3e, - 0xd1, 0x56, 0xcf, 0x78, 0xae, 0xfb, 0x4a, 0x65, - 0x50, 0xd9, 0x7b, 0x87, 0x99, 0x79, 0x77, 0xee - ]), - secretKey: new Uint8Array([ - 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, - // public part - 0x2f, 0x8c, 0x61, 0x29, 0xd8, 0x16, 0xcf, 0x51, - 0xc3, 0x74, 0xbc, 0x7f, 0x08, 0xc3, 0xe6, 0x3e, - 0xd1, 0x56, 0xcf, 0x78, 0xae, 0xfb, 0x4a, 0x65, - 0x50, 0xd9, 0x7b, 0x87, 0x99, 0x79, 0x77, 0xee - ]) - }; - - beforeEach(async () => { - await waitReady(); - }); - - it('generates a valid publicKey/secretKey pair (u8a)', () => { - expect( - naclKeypairFromSeed(TEST) - ).toEqual(RESULT); - }); -}); diff --git a/packages/util-crypto/src/nacl/keypair/fromSeed.ts b/packages/util-crypto/src/nacl/keypair/fromSeed.ts deleted file mode 100644 index 50be7c903e..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromSeed.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import nacl from 'tweetnacl'; -import { isReady, ed25519KeypairFromSeed } from '@plugnet/wasm-crypto'; - -/** - * @name naclKeypairFromSeed - * @summary Creates a new public/secret keypair from a seed. - * @description - * Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed. - * @example - *
- * - * ```javascript - * import { naclKeypairFromSeed } from '@plugnet/util-crypto'; - * - * naclKeypairFromSeed(...); // => { secretKey: [...], publicKey: [...] } - * ``` - */ -export default function naclKeypairFromSeed (seed: Uint8Array): Keypair { - if (isReady()) { - const full = ed25519KeypairFromSeed(seed); - - return { - publicKey: full.slice(32), - secretKey: full.slice(0, 64) - }; - } - - return nacl.sign.keyPair.fromSeed(seed); -} diff --git a/packages/util-crypto/src/nacl/keypair/fromString.spec.ts b/packages/util-crypto/src/nacl/keypair/fromString.spec.ts deleted file mode 100644 index a1a2c3e0b8..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromString.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { naclKeypairFromString } from '..'; - -describe('naclKeypairFromSeed', () => { - it('generates a valid publicKey/secretKey pair', () => { - expect( - naclKeypairFromString('test') - ).toEqual({ - publicKey: new Uint8Array([188, 108, 179, 142, 36, 142, 76, 87, 77, 193, 147, 139, 254, 110, 196, 217, 117, 233, 167, 165, 250, 150, 247, 237, 198, 68, 129, 4, 211, 209, 136, 48]), - secretKey: new Uint8Array([146, 139, 32, 54, 105, 67, 226, 175, 209, 30, 188, 14, 174, 46, 83, 169, 59, 241, 119, 164, 252, 243, 91, 204, 100, 213, 3, 112, 78, 101, 226, 2, 188, 108, 179, 142, 36, 142, 76, 87, 77, 193, 147, 139, 254, 110, 196, 217, 117, 233, 167, 165, 250, 150, 247, 237, 198, 68, 129, 4, 211, 209, 136, 48]) - }); - }); -}); diff --git a/packages/util-crypto/src/nacl/keypair/fromString.ts b/packages/util-crypto/src/nacl/keypair/fromString.ts deleted file mode 100644 index 4165aa6562..0000000000 --- a/packages/util-crypto/src/nacl/keypair/fromString.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import { stringToU8a } from '@plugnet/util'; - -import blake2AsU8a from '../../blake2/asU8a'; -import fromSeed from './fromSeed'; - -/** - * @name naclKeypairFromString - * @summary Creates a new public/secret keypair from a string. - * @description - * Returns a object containing a `publicKey` & `secretKey` generated from the supplied string. The string is hashed and the value used as the input seed. - * @example - *
- * - * ```javascript - * import { naclKeypairFromString } from '@plugnet/util-crypto'; - * - * naclKeypairFromString('test'); // => { secretKey: [...], publicKey: [...] } - * ``` - */ -export default function naclKeypairFromString (value: string): Keypair { - return fromSeed( - blake2AsU8a( - stringToU8a(value), - 256 - ) - ); -} diff --git a/packages/util-crypto/src/nacl/sign.spec.ts b/packages/util-crypto/src/nacl/sign.spec.ts deleted file mode 100644 index 2e6cfd71ed..0000000000 --- a/packages/util-crypto/src/nacl/sign.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { naclSign, naclKeypairFromSeed } from '.'; - -describe('naclSign', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a valid signature for the message', () => { - expect( - naclSign( - new Uint8Array([0x61, 0x62, 0x63, 0x64]), - naclKeypairFromSeed( - stringToU8a('12345678901234567890123456789012') - ) - ) - ).toEqual( - new Uint8Array([28, 58, 206, 239, 249, 70, 59, 191, 166, 40, 219, 218, 235, 170, 25, 79, 10, 94, 9, 197, 34, 126, 1, 150, 246, 68, 28, 238, 36, 26, 172, 163, 168, 90, 202, 211, 126, 246, 57, 212, 43, 24, 88, 197, 240, 113, 118, 76, 37, 81, 91, 110, 236, 50, 144, 134, 100, 223, 220, 238, 34, 185, 211, 7]) - ); - }); -}); diff --git a/packages/util-crypto/src/nacl/sign.ts b/packages/util-crypto/src/nacl/sign.ts deleted file mode 100644 index f8b2471882..0000000000 --- a/packages/util-crypto/src/nacl/sign.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import nacl from 'tweetnacl'; -import { assert } from '@plugnet/util'; -import { isReady, ed25519Sign } from '@plugnet/wasm-crypto'; - -/** - * @name naclSign - * @summary Signs a message using the supplied secretKey - * @description - * Returns message signature of `message`, using the `secretKey`. - * @example - *
- * - * ```javascript - * import { naclSign } from '@plugnet/util-crypto'; - * - * naclSign([...], [...]); // => [...] - * ``` - */ -export default function naclSign (message: Uint8Array, { publicKey, secretKey }: Partial): Uint8Array { - assert(secretKey, 'Expected valid secretKey'); - - return isReady() - ? ed25519Sign(publicKey as Uint8Array, (secretKey as Uint8Array).subarray(0, 32), message) - : nacl.sign.detached(message, secretKey as Uint8Array); -} diff --git a/packages/util-crypto/src/nacl/verify.spec.ts b/packages/util-crypto/src/nacl/verify.spec.ts deleted file mode 100644 index 634ea94d8c..0000000000 --- a/packages/util-crypto/src/nacl/verify.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { naclVerify, naclKeypairFromSeed } from '.'; - -describe('naclSign', () => { - let publicKey: Uint8Array; - let signature: Uint8Array; - - beforeEach(async () => { - await waitReady(); - - publicKey = naclKeypairFromSeed( - stringToU8a('12345678901234567890123456789012') - ).publicKey; - signature = new Uint8Array([28, 58, 206, 239, 249, 70, 59, 191, 166, 40, 219, 218, 235, 170, 25, 79, 10, 94, 9, 197, 34, 126, 1, 150, 246, 68, 28, 238, 36, 26, 172, 163, 168, 90, 202, 211, 126, 246, 57, 212, 43, 24, 88, 197, 240, 113, 118, 76, 37, 81, 91, 110, 236, 50, 144, 134, 100, 223, 220, 238, 34, 185, 211, 7]); - }); - - it('validates a correctly signed message', () => { - expect( - naclVerify( - new Uint8Array([0x61, 0x62, 0x63, 0x64]), - signature, - publicKey - ) - ).toEqual(true); - }); - - it('fails a correctly signed message (message changed)', () => { - expect( - naclVerify( - new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]), - signature, - publicKey - ) - ).toEqual(false); - }); - - it('fails a correctly signed message (signature changed)', () => { - signature[0] = 0xff; - - expect( - naclVerify( - new Uint8Array([0x61, 0x62, 0x63, 0x64]), - signature, - publicKey - ) - ).toEqual(false); - }); -}); diff --git a/packages/util-crypto/src/nacl/verify.ts b/packages/util-crypto/src/nacl/verify.ts deleted file mode 100644 index 8395380921..0000000000 --- a/packages/util-crypto/src/nacl/verify.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import nacl from 'tweetnacl'; -import { isReady, ed25519Verify } from '@plugnet/wasm-crypto'; - -/** - * @name naclSign - * @summary Verifies the signature on the supplied message. - * @description - * Verifies the `signature` on `message` with the supplied `plublicKey`. Returns `true` on sucess, `false` otherwise. - * @example - *
- * - * ```javascript - * import { naclVerify } from '@plugnet/util-crypto'; - * - * naclVerify([...], [...], [...]); // => true/false - * ``` - */ -export default function naclVerify (message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean { - return isReady() - ? ed25519Verify(signature, message, publicKey) - : nacl.sign.detached.verify(message, signature, publicKey); -} diff --git a/packages/util-crypto/src/polyfill.ts b/packages/util-crypto/src/polyfill.ts deleted file mode 100644 index 04693b79e2..0000000000 --- a/packages/util-crypto/src/polyfill.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '@polkadot/wasm-crypto/crypto-polyfill'; diff --git a/packages/util-crypto/src/random/asHex.spec.ts b/packages/util-crypto/src/random/asHex.spec.ts deleted file mode 100644 index 07e211fda1..0000000000 --- a/packages/util-crypto/src/random/asHex.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isHex } from '@plugnet/util'; - -import { randomAsHex } from '.'; - -describe('randomAsBuffer', () => { - it('generated results does not match', () => { - expect( - randomAsHex() - ).not.toEqual( - randomAsHex() - ); - }); - - it('is a valid hex number', () => { - expect( - isHex( - randomAsHex() - ) - ).toEqual(true); - }); - - it('generates 32 bytes by default', () => { - expect( - randomAsHex() - ).toHaveLength(32 * 2 + 2); - }); - - it('generates with the supplied length', () => { - expect( - randomAsHex(66) - ).toHaveLength(66 * 2 + 2); - }); -}); diff --git a/packages/util-crypto/src/random/asHex.ts b/packages/util-crypto/src/random/asHex.ts deleted file mode 100644 index 9762030956..0000000000 --- a/packages/util-crypto/src/random/asHex.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import randomAsU8a from './asU8a'; - -/** - * @name randomAsHex - * @summary Creates a hex string filled with random bytes. - * @description - * Returns a hex string with the specified (optional) length filled with random bytes. - * @example - *
- * - * ```javascript - * import { randomAsHex } from '@plugnet/util-crypto'; - * - * randomAsHex(); // => 0x... - * ``` - */ -export default function randomAsHex (length: number = 32): string { - return u8aToHex( - randomAsU8a(length) - ); -} diff --git a/packages/util-crypto/src/random/asNumber.spec.ts b/packages/util-crypto/src/random/asNumber.spec.ts deleted file mode 100644 index 0ceb26d2b5..0000000000 --- a/packages/util-crypto/src/random/asNumber.spec.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { randomAsNumber } from '.'; - -describe('randomAsNumber', () => { - it('generates subsequent non-matching numbers', () => { - expect( - randomAsNumber() - ).not.toEqual( - randomAsNumber() - ); - }); -}); diff --git a/packages/util-crypto/src/random/asNumber.ts b/packages/util-crypto/src/random/asNumber.ts deleted file mode 100644 index 0d74549767..0000000000 --- a/packages/util-crypto/src/random/asNumber.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; -import { hexToBn } from '@plugnet/util'; - -import randomAsHex from './asHex'; - -const BN_53 = new BN(0b11111111111111111111111111111111111111111111111111111); - -/** - * @name randomAsNumber - * @summary Creates a random number from random bytes. - * @description - * Returns a random number generated from the secure bytes. - * @example - *
- * - * ```javascript - * import { randomAsNumber } from '@plugnet/util-crypto'; - * - * randomAsNumber(); // => - * ``` - */ -export default function randomAsNumber (): number { - return hexToBn( - randomAsHex(8) - ).and(BN_53).toNumber(); -} diff --git a/packages/util-crypto/src/random/asU8a.spec.ts b/packages/util-crypto/src/random/asU8a.spec.ts deleted file mode 100644 index 1e4f3d159e..0000000000 --- a/packages/util-crypto/src/random/asU8a.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isU8a } from '@plugnet/util'; - -import { randomAsU8a } from '.'; - -describe('randomAsU8a', () => { - it('generates a Uint8Array', () => { - expect( - isU8a(randomAsU8a()) - ).toEqual(true); - }); - - it('generated results does not match', () => { - expect( - randomAsU8a() - ).not.toEqual( - randomAsU8a() - ); - }); - - it('generates 32 bytes by default', () => { - expect( - randomAsU8a() - ).toHaveLength(32); - }); - - it('generates with the suuplied length', () => { - expect( - randomAsU8a(66) - ).toHaveLength(66); - }); -}); diff --git a/packages/util-crypto/src/random/asU8a.ts b/packages/util-crypto/src/random/asU8a.ts deleted file mode 100644 index 8f85c0edf9..0000000000 --- a/packages/util-crypto/src/random/asU8a.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import nacl from 'tweetnacl'; - -/** - * @name randomAsU8a - * @summary Creates a Uint8Array filled with random bytes. - * @description - * Returns a `Uint8Array` with the specified (optional) length filled with random bytes. - * @example - *
- * - * ```javascript - * import { randomAsU8a } from '@plugnet/util-crypto'; - * - * randomAsU8a(); // => Uint8Array([...]) - * ``` - */ -export default function randomAsU8a (length: number = 32): Uint8Array { - return nacl.randomBytes(length); -} diff --git a/packages/util-crypto/src/random/index.ts b/packages/util-crypto/src/random/index.ts deleted file mode 100644 index f2ec83bbb9..0000000000 --- a/packages/util-crypto/src/random/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Returns a sequence of secure random bytes in a variety of formats - */ - -export { default as randomAsHex } from './asHex'; -export { default as randomAsNumber } from './asNumber'; -export { default as randomAsU8a } from './asU8a'; diff --git a/packages/util-crypto/src/schnorrkel/deriveHard.ts b/packages/util-crypto/src/schnorrkel/deriveHard.ts deleted file mode 100644 index de0ce190f6..0000000000 --- a/packages/util-crypto/src/schnorrkel/deriveHard.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import '../polyfill'; - -import { sr25519DeriveKeypairHard } from '@plugnet/wasm-crypto'; - -import keypairFromU8a from './keypair/fromU8a'; -import keypairToU8a from './keypair/toU8a'; - -export default function deriveHard (keypair: Keypair, chainCode: Uint8Array): Keypair { - return keypairFromU8a( - sr25519DeriveKeypairHard(keypairToU8a(keypair), chainCode) - ); -} diff --git a/packages/util-crypto/src/schnorrkel/deriveSoft.ts b/packages/util-crypto/src/schnorrkel/deriveSoft.ts deleted file mode 100644 index 95be091e0e..0000000000 --- a/packages/util-crypto/src/schnorrkel/deriveSoft.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import '../polyfill'; - -import { sr25519DeriveKeypairSoft } from '@plugnet/wasm-crypto'; - -import keypairFromU8a from './keypair/fromU8a'; -import keypairToU8a from './keypair/toU8a'; - -export default function deriveSoft (keypair: Keypair, chainCode: Uint8Array): Keypair { - return keypairFromU8a( - sr25519DeriveKeypairSoft(keypairToU8a(keypair), chainCode) - ); -} diff --git a/packages/util-crypto/src/schnorrkel/index.ts b/packages/util-crypto/src/schnorrkel/index.ts deleted file mode 100644 index 2a721b3f77..0000000000 --- a/packages/util-crypto/src/schnorrkel/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -export { default as schnorrkelDeriveHard } from './deriveHard'; -export { default as schnorrkelDeriveSoft } from './deriveSoft'; -export { default as schnorrkelKeypairFromSeed } from './keypair/fromSeed'; -export { default as schnorrkelSign } from './sign'; -export { default as schnorrkelVerify } from './verify'; diff --git a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts b/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts deleted file mode 100644 index d4f5b80cf7..0000000000 --- a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a, u8aToHex } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { mnemonicToMiniSecret } from '../../mnemonic'; -import { schnorrkelKeypairFromSeed } from '..'; -import tests from './testing'; - -describe('schnorrkelKeypairFromSeed', () => { - const TEST = stringToU8a('12345678901234567890123456789012'); - const RESULT = { - publicKey: new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99]), - secretKey: new Uint8Array([240, 16, 102, 96, 195, 221, 162, 63, 22, 218, 169, 172, 91, 129, 27, 150, 48, 119, 245, 188, 10, 248, 159, 133, 128, 79, 13, 232, 228, 36, 240, 80, 249, 141, 102, 243, 148, 66, 80, 111, 249, 71, 253, 145, 31, 24, 199, 167, 165, 218, 99, 154, 99, 232, 211, 180, 226, 51, 247, 65, 67, 217, 81, 193]) - }; - - beforeEach(async () => { - return waitReady(); - }); - - it('generates a valid publicKey/secretKey pair (u8a)', () => { - expect( - schnorrkelKeypairFromSeed(TEST) - ).toEqual(RESULT); - }); - - tests.forEach(([mnemonic, , , secret], index) => { - it(`creates valid against known (${index})`, () => { - const seed = mnemonicToMiniSecret(mnemonic, 'Substrate'); - const pair = schnorrkelKeypairFromSeed(seed); - - expect( - u8aToHex(pair.secretKey) - ).toEqual(secret); - }); - }); -}); diff --git a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.ts b/packages/util-crypto/src/schnorrkel/keypair/fromSeed.ts deleted file mode 100644 index d775d6f6a6..0000000000 --- a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import '../../polyfill'; - -import { sr25519KeypairFromSeed } from '@plugnet/wasm-crypto'; - -import keypairFromU8a from './fromU8a'; - -/** - * @name schnorrkelKeypairFromSeed - * @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed. - */ -export default function schnorrkelKeypairFromSeed (seed: Uint8Array): Keypair { - return keypairFromU8a( - sr25519KeypairFromSeed(seed) - ); -} diff --git a/packages/util-crypto/src/schnorrkel/keypair/fromU8a.ts b/packages/util-crypto/src/schnorrkel/keypair/fromU8a.ts deleted file mode 100644 index bdf4de5bc2..0000000000 --- a/packages/util-crypto/src/schnorrkel/keypair/fromU8a.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -const SEC_LEN = 64; -const PUB_LEN = 32; - -export default function schnorrkelKeypairFromU8a (full: Uint8Array): Keypair { - return { - publicKey: full.slice(SEC_LEN, SEC_LEN + PUB_LEN), - secretKey: full.slice(0, SEC_LEN) - }; -} diff --git a/packages/util-crypto/src/schnorrkel/keypair/testing.ts b/packages/util-crypto/src/schnorrkel/keypair/testing.ts deleted file mode 100644 index f45850f5df..0000000000 --- a/packages/util-crypto/src/schnorrkel/keypair/testing.ts +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// mnemonic, entropy, seed, secret (expanded) -type Test = [string, string, string, string]; - -const tests: Array = [ - [ - 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', - '0x00000000000000000000000000000000', - '0x44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453', - '0xb0b3174fe43c15938bb0d0cc5b6f7ac7295f557ee1e6fdeb24fb73f4e0cb2b6ec40ffb9da4af6d411eae8e292750fd105ff70fe93f337b5b590f5a9d9030c750' - ], - [ - 'legal winner thank year wave sausage worth useful legal winner thank yellow', - '0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', - '0x4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b780416850f1e26c1f4b8d88ece681cb058ab66d6182bc2ce5a03181f7b74c27576b5c8bf', - '0x20666c9dd63c5b04a6a14377579af14aba60707752d134726304d0804992e26f9092c47fbb9e14c02fd53c702c8a3cfca4735638599da5c4362e0d0560dceb58' - ], - [ - 'letter advice cage absurd amount doctor acoustic avoid letter advice cage above', - '0x80808080808080808080808080808080', - '0x27f3eb595928c60d5bc91a4d747da40ed236328183046892ed6cd5aa9ae38122acd1183adf09a89839acb1e6eaa7fb563cc958a3f9161248d5a036e0d0af533d', - '0x709e8254d0a9543c6b35b145dd23349e6369d487a1d10b0cfe09c05ff521f4691ad8bb8221339af38fc48510ec2dfc3104bb94d38f1fa241ceb252943df7b6b5' - ], - [ - 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong', - '0xffffffffffffffffffffffffffffffff', - '0x227d6256fd4f9ccaf06c45eaa4b2345969640462bbb00c5f51f43cb43418c7a753265f9b1e0c0822c155a9cabc769413ecc14553e135fe140fc50b6722c6b9df', - '0x88206f4b4102ad30ee40b4b5943c5259db77fd576d95d79eeea00160197e406308821814dea9442675a5d3fa375b3bd65ffe92be43e07dbf6bb4ab84e9d4449d' - ], - [ - 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent', - '0x000000000000000000000000000000000000000000000000', - '0x44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453', - '0xb0b3174fe43c15938bb0d0cc5b6f7ac7295f557ee1e6fdeb24fb73f4e0cb2b6ec40ffb9da4af6d411eae8e292750fd105ff70fe93f337b5b590f5a9d9030c750' - ], - [ - 'legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will', - '0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', - '0xcb1d50e14101024a88905a098feb1553d4306d072d7460e167a60ccb3439a6817a0afc59060f45d999ddebc05308714733c9e1e84f30feccddd4ad6f95c8a445', - '0x50dcb74f223740d6a256000a2f1ccdb60044b39ce3aad71a3bd7761848d5f55d5a34f96e0b96ecb45d7a142e07ddfde734f9525f9f88310ab50e347da5789d3e' - ], - [ - 'letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always', - '0x808080808080808080808080808080808080808080808080', - '0x9ddecf32ce6bee77f867f3c4bb842d1f0151826a145cb4489598fe71ac29e3551b724f01052d1bc3f6d9514d6df6aa6d0291cfdf997a5afdb7b6a614c88ab36a', - '0x88112947a30e864b511838b6daf6e1e13801ae003d6d9b73eb5892c355f7e37ab3bb71200092d004467b06fe67bc153ee4e2bb7af2f544815b0dde276d2dae75' - ], - [ - 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when', - '0xffffffffffffffffffffffffffffffffffffffffffffffff', - '0x8971cb290e7117c64b63379c97ed3b5c6da488841bd9f95cdc2a5651ac89571e2c64d391d46e2475e8b043911885457cd23e99a28b5a18535fe53294dc8e1693', - '0x4859cdeda3f957b7ffcd2d59257c30e43996796f38e1be5c6136c9bf3744e047ce9a52c11793c98d0dc8caee927576ce46ef2e5f4b3f1d5e4b1344b2c31ebe8e' - ], - [ - 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art', - '0x0000000000000000000000000000000000000000000000000000000000000000', - '0x44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453', - '0xb0b3174fe43c15938bb0d0cc5b6f7ac7295f557ee1e6fdeb24fb73f4e0cb2b6ec40ffb9da4af6d411eae8e292750fd105ff70fe93f337b5b590f5a9d9030c750' - ], - [ - 'legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title', - '0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', - '0x3037276a5d05fcd7edf51869eb841bdde27c574dae01ac8cfb1ea476f6bea6ef57ab9afe14aea1df8a48f97ae25b37d7c8326e49289efb25af92ba5a25d09ed3', - '0xe8962ace15478f69fa42ddd004aad2c285c9f5a02e0712860e83fbec041f89489046aa57b21db2314d93aeb4a2d7cbdab21d4856e8e151894abd17fb04ae65e1' - ], - [ - 'letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless', - '0x8080808080808080808080808080808080808080808080808080808080808080', - '0x2c9c6144a06ae5a855453d98c3dea470e2a8ffb78179c2e9eb15208ccca7d831c97ddafe844ab933131e6eb895f675ede2f4e39837bb5769d4e2bc11df58ac42', - '0x78667314bf1e52e38d29792cdf294efcaddadc4fa9ce48c5f2bef4daad7ed95d1db960d6f6f895c1a9d2a3ddcc0398ba6578580ea1f03f65ea9a68e97cf3f840' - ], - [ - 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote', - '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', - '0x047e89ef7739cbfe30da0ad32eb1720d8f62441dd4f139b981b8e2d0bd412ed4eb14b89b5098c49db2301d4e7df4e89c21e53f345138e56a5e7d63fae21c5939', - '0xe09f4ae0d4e22f6c9bbc4251c880e73d93d10fdf7f152c393ce36e4e942b3155a6f4b48e6c6ebce902a10d4ab46ef59cd154c15aeb8f7fcd4e1e26342d40806d' - ], - [ - 'ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic', - '0x9e885d952ad362caeb4efe34a8e91bd2', - '0xf4956be6960bc145cdab782e649a5056598fd07cd3f32ceb73421c3da27833241324dc2c8b0a4d847eee457e6d4c5429f5e625ece22abaa6a976e82f1ec5531d', - '0xb0eb046f48eacb7ad6c4da3ff92bfc29c9ad471bae3e554d5d63e58827160c70c7e5165598761f96b5659ab28c474f50e89ee13c67e30bca40fdcf4335835649' - ], - [ - 'gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog', - '0x6610b25967cdcca9d59875f5cb50b0ea75433311869e930b', - '0xfbcc5229ade0c0ff018cb7a329c5459f91876e4dde2a97ddf03c832eab7f26124366a543f1485479c31a9db0d421bda82d7e1fe562e57f3533cb1733b001d84d', - '0xd8da734285a13967647dd906288e1ac871e1945d0c6b72fa259de4051a9b75431be0c4eb40b1ca38c780f445e3e2809282b9efef4dcc3538355e68094f1e79fa' - ], - [ - 'hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length', - '0x68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c', - '0x7c60c555126c297deddddd59f8cdcdc9e3608944455824dd604897984b5cc369cad749803bb36eb8b786b570c9cdc8db275dbe841486676a6adf389f3be3f076', - '0x883b72fa7fb06b6abd0fc2cdb0018b3578e086e93074256bbbb8c68e53c04a56391bc0d19d7b2fa22a8148ccbe191d969c4323faca1935a576cc1b24301f203a' - ], - [ - 'scheme spot photo card baby mountain device kick cradle pact join borrow', - '0xc0ba5a8e914111210f2bd131f3d5e08d', - '0xc12157bf2506526c4bd1b79a056453b071361538e9e2c19c28ba2cfa39b5f23034b974e0164a1e8acd30f5b4c4de7d424fdb52c0116bfc6a965ba8205e6cc121', - '0x7039a64150089f8d43188af964c7b8e2b8c9ba20aede085baca5672e978a47576c7193c3e557f37cdeeee5e5131b854e4309efc55259b050474e1f0884a7a621' - ], - [ - 'horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave', - '0x6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3', - '0x23766723e970e6b79dec4d5e4fdd627fd27d1ee026eb898feb9f653af01ad22080c6f306d1061656d01c4fe9a14c05f991d2c7d8af8730780de4f94cd99bd819', - '0xe07a1f3073edad5b63585cdf1d5e6f8e50e3145de550fc8eb1fb430cce62d76d251904272c5d25fd634615d413bb31a2bc7b5d6eeb2f6ddc68a2b95ac6bd49bc' - ], - [ - 'panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside', - '0x9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863', - '0xf4c83c86617cb014d35cd87d38b5ef1c5d5c3d58a73ab779114438a7b358f457e0462c92bddab5a406fe0e6b97c71905cf19f925f356bc673ceb0e49792f4340', - '0x607f8595266ac0d4aa91bf4fddbd2a868889317f40099979be9743c46c418976e6ff3717bd11b94b418f91c8b88eae142cecb19104820997ddf5a379dd9da5ae' - ], - [ - 'cat swing flag economy stadium alone churn speed unique patch report train', - '0x23db8160a31d3e0dca3688ed941adbf3', - '0x719d4d4de0638a1705bf5237262458983da76933e718b2d64eb592c470f3c5d222e345cc795337bb3da393b94375ff4a56cfcd68d5ea25b577ee9384d35f4246', - '0xd078b66bb357f1f06e897a6fdfa2f3dfb0da05836ded1fd0793373068b7e854e783a548a6d194f142e1ba78bf42a49fa58e3673b363ba6f6494efffa28f168df' - ], - [ - 'light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access', - '0x8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0', - '0x7ae1291db32d16457c248567f2b101e62c5549d2a64cd2b7605d503ec876d58707a8d663641e99663bc4f6cc9746f4852e75e7e54de5bc1bd3c299c9a113409e', - '0x5095fe4d0144b06e82aa4753d595fd10de9bba3733eba8ce0784417182317e725fac31b2fb53f4856a5e38866501425b485f4d2eaf2666a9f20ae68f4331ed2c' - ], - [ - 'all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform', - '0x066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad', - '0xa911a5f4db0940b17ecb79c4dcf9392bf47dd18acaebdd4ef48799909ebb49672947cc15f4ef7e8ef47103a1a91a6732b821bda2c667e5b1d491c54788c69391', - '0x8844cb50f3ba8030ab61afee623534836d4ea3677d42bae470fc5e251ea0ca7ec9ea65c8c40be191c7c8683165848279ced81f3a121c9450078a496b6c59f610' - ], - [ - 'vessel ladder alter error federal sibling chat ability sun glass valve picture', - '0xf30f8c1da665478f49b001d94c5fc452', - '0x4e2314ca7d9eebac6fe5a05a5a8d3546bc891785414d82207ac987926380411e559c885190d641ff7e686ace8c57db6f6e4333c1081e3d88d7141a74cf339c8f', - '0x18917f0c7480c95cd4d98bdc7df773c366d33590252707da1358eb58b43a7b765e3c513878541bfbfb466bb4206f581edf9bf601409c72afac130bcc8b5661b5' - ], - [ - 'scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump', - '0xc10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05', - '0x7a83851102849edc5d2a3ca9d8044d0d4f00e5c4a292753ed3952e40808593251b0af1dd3c9ed9932d46e8608eb0b928216a6160bd4fc775a6e6fbd493d7c6b2', - '0xb0bf86b0955413fc95144bab124e82042d0cce9c292c1bfd0874ae5a95412977e7bc109aeef33c7c90be952a83f3fe528419776520de721ef6ec9e814749c3fc' - ], - [ - 'void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold', - '0xf585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f', - '0x938ba18c3f521f19bd4a399c8425b02c716844325b1a65106b9d1593fbafe5e0b85448f523f91c48e331995ff24ae406757cff47d11f240847352b348ff436ed', - '0xc07ba4a979657576f4f7446e3bd2672c87131fa0f472a8bc1f2e9b28c11fb04c66da12cd280662196a5888d8a77178dab8034ed42b11d1654a31db6e1ff4d4c5' - ] -]; - -export default tests; diff --git a/packages/util-crypto/src/schnorrkel/keypair/toU8a.ts b/packages/util-crypto/src/schnorrkel/keypair/toU8a.ts deleted file mode 100644 index bc6e551392..0000000000 --- a/packages/util-crypto/src/schnorrkel/keypair/toU8a.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../../types'; - -import { u8aConcat } from '@plugnet/util'; - -export default function schnorrkelKeypairToU8a ({ publicKey, secretKey }: Keypair): Uint8Array { - return u8aConcat(secretKey, publicKey).slice(); -} diff --git a/packages/util-crypto/src/schnorrkel/sign.ts b/packages/util-crypto/src/schnorrkel/sign.ts deleted file mode 100644 index 9adba0af37..0000000000 --- a/packages/util-crypto/src/schnorrkel/sign.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Keypair } from '../types'; - -import '../polyfill'; - -import { assert } from '@plugnet/util'; -import { sr25519Sign } from '@plugnet/wasm-crypto'; - -/** - * @name schnorrkelSign - * @description Returns message signature of `message`, using the supplied pair - */ -export default function schnorrkelSign (message: Uint8Array, { publicKey, secretKey }: Partial): Uint8Array { - assert(publicKey && publicKey.length === 32, 'Expected valid publicKey, 32-bytes'); - assert(secretKey && secretKey.length === 64, 'Expected valid secretKey, 64-bytes'); - - return sr25519Sign(publicKey as Uint8Array, secretKey as Uint8Array, message); -} diff --git a/packages/util-crypto/src/schnorrkel/signVerify.spec.ts b/packages/util-crypto/src/schnorrkel/signVerify.spec.ts deleted file mode 100644 index e56b10a08e..0000000000 --- a/packages/util-crypto/src/schnorrkel/signVerify.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import randomAsU8a from '../random/asU8a'; -import pairFromSeed from './keypair/fromSeed'; -import sign from './sign'; -import verify from './verify'; - -const MESSAGE = stringToU8a('this is a message'); - -describe('sign and verify', () => { - beforeEach(async () => { - return waitReady(); - }); - - it('has 64-byte signatures', () => { - const pair = pairFromSeed(randomAsU8a()); - - expect(sign(MESSAGE, pair)).toHaveLength(64); - }); - - it('can sign and verify a message', () => { - const pair = pairFromSeed(randomAsU8a()); - const signature = sign(MESSAGE, pair); - - expect(verify(MESSAGE, signature, pair.publicKey)).toBe(true); - }); -}); diff --git a/packages/util-crypto/src/schnorrkel/verify.ts b/packages/util-crypto/src/schnorrkel/verify.ts deleted file mode 100644 index 7575643281..0000000000 --- a/packages/util-crypto/src/schnorrkel/verify.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import '../polyfill'; - -import { sr25519Verify } from '@plugnet/wasm-crypto'; - -/** - * @name schnorrkelVerify - * @description Verifies the signature of `message`, using the supplied pair - */ -export default function schnorrkelVerify (message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean { - return sr25519Verify(signature, message, publicKey); -} diff --git a/packages/util-crypto/src/secp256k1/index.ts b/packages/util-crypto/src/secp256k1/index.ts deleted file mode 100644 index 8c093b6fe4..0000000000 --- a/packages/util-crypto/src/secp256k1/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export { default as secp256k1Recover } from './recover'; diff --git a/packages/util-crypto/src/secp256k1/recover.ts b/packages/util-crypto/src/secp256k1/recover.ts deleted file mode 100644 index 2287199549..0000000000 --- a/packages/util-crypto/src/secp256k1/recover.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import secp256k1 from 'secp256k1'; -import { u8aToBuffer, u8aToU8a } from '@plugnet/util'; - -/** - * @name secp256k1Recover - * @description Recovers a publicKey from the supplied signature - */ -export default function secp256k1Recover (message: Uint8Array, signature: Uint8Array, recovery: number): Uint8Array { - return u8aToU8a( - secp256k1.recover(u8aToBuffer(message), u8aToBuffer(signature), recovery) - ); -} diff --git a/packages/util-crypto/src/sha512/asU8a.spec.ts b/packages/util-crypto/src/sha512/asU8a.spec.ts deleted file mode 100644 index ae880fbf39..0000000000 --- a/packages/util-crypto/src/sha512/asU8a.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { waitReady } from '@plugnet/wasm-crypto'; - -import { sha512AsU8a } from '.'; - -describe('sha512AsU8a', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('creates a sha-512 hash', () => { - expect( - sha512AsU8a( - Uint8Array.from([0x61, 0x62, 0x63, 0x64]) - ) - ).toEqual( - Uint8Array.from([ - 216, 2, 47, 32, 96, 173, 110, 253, 41, 122, 183, 61, 204, 83, 85, 201, 178, 20, 5, 75, 13, 23, 118, 161, 54, 166, 105, 210, 106, 125, 59, 20, 247, 58, 160, 208, 235, 255, 25, 238, 51, 51, 104, 240, 22, 75, 100, 25, 169, 109, 164, 158, 62, 72, 23, 83, 231, 233, 107, 113, 107, 220, 203, 111 - ]) - ); - }); -}); diff --git a/packages/util-crypto/src/sha512/asU8a.ts b/packages/util-crypto/src/sha512/asU8a.ts deleted file mode 100644 index b7eb99a280..0000000000 --- a/packages/util-crypto/src/sha512/asU8a.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import nacl from 'tweetnacl'; -import { isReady, sha512 } from '@plugnet/wasm-crypto'; - -/** - * @name sha512AsU8a - * @summary Creates sha-512 hash of the input. - * @description - * Returns a sha-512 `Uint8Array` from the supplied data. - * @example - *
- * - * ```javascript - * import { sha512AsU8a } from '@plugnet/util-crypto'; - * - * sha512AsU8a(Uint8Array.from([...])); // => Uint8Array([...]) - * ``` - */ -export default function sha512AsU8a (data: Uint8Array): Uint8Array { - return isReady() - ? sha512(data) - : nacl.hash(data); -} diff --git a/packages/util-crypto/src/sha512/index.ts b/packages/util-crypto/src/sha512/index.ts deleted file mode 100644 index 887f59f295..0000000000 --- a/packages/util-crypto/src/sha512/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Implements Sha-512 hashing functions for a variety of input and outputs - */ - -export { default as sha512AsU8a } from './asU8a'; diff --git a/packages/util-crypto/src/types.ts b/packages/util-crypto/src/types.ts deleted file mode 100644 index b010a8c13e..0000000000 --- a/packages/util-crypto/src/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export type Keypair = { - publicKey: Uint8Array; - secretKey: Uint8Array; -}; - -export type Seedpair = { - publicKey: Uint8Array; - seed: Uint8Array; -}; - -export type KeypairType = 'ed25519' | 'sr25519'; diff --git a/packages/util-crypto/src/xxhash/asHex.spec.ts b/packages/util-crypto/src/xxhash/asHex.spec.ts deleted file mode 100644 index 62acb13fe4..0000000000 --- a/packages/util-crypto/src/xxhash/asHex.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { waitReady } from '@plugnet/wasm-crypto'; - -import { xxhashAsHex } from '.'; - -describe('xxhashAsHex', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a 64-bit value by default', () => { - expect( - xxhashAsHex('abc') - ).toEqual('0x990977adf52cbc44'); - }); - - it('returns a 128-bit value (as specified)', () => { - expect( - xxhashAsHex('abc', 128) - ).toEqual('0x990977adf52cbc440889329981caa9be'); - }); - - it('returns a 256-bit value (as specified)', () => { - expect( - xxhashAsHex('abc', 256) - ).toEqual('0x990977adf52cbc440889329981caa9bef7da5770b2b8a05303b75d95360dd62b'); - }); -}); diff --git a/packages/util-crypto/src/xxhash/asHex.ts b/packages/util-crypto/src/xxhash/asHex.ts deleted file mode 100644 index f9775d8c7b..0000000000 --- a/packages/util-crypto/src/xxhash/asHex.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '@plugnet/util'; - -import xxhashAsU8a from './asU8a'; - -/** - * @name xxhashAsHex - * @summary Creates a xxhash64 hex from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a hex string with the specified `bitLength`. - * @example - *
- * - * ```javascript - * import { xxhashAsHex } from '@plugnet/util-crypto'; - * - * xxhashAsHex('abc'); // => 0x44bc2cf5ad770999 - * ``` - */ -export default function xxhashAsHex (data: Buffer | Uint8Array | string, bitLength: number = 64): string { - return u8aToHex( - xxhashAsU8a(data, bitLength) - ); -} diff --git a/packages/util-crypto/src/xxhash/asU8a.spec.ts b/packages/util-crypto/src/xxhash/asU8a.spec.ts deleted file mode 100644 index 0326f409db..0000000000 --- a/packages/util-crypto/src/xxhash/asU8a.spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a } from '@plugnet/util'; -import { waitReady } from '@plugnet/wasm-crypto'; - -import { xxhashAsU8a } from '.'; - -describe('xxhashAsU8a', () => { - beforeEach(async () => { - await waitReady(); - }); - - it('returns a 64-bit value by default', () => { - expect( - xxhashAsU8a('abc') - ).toEqual( - hexToU8a('0x990977adf52cbc44') - ); - }); - - it('returns a 128-bit value (as specified)', () => { - expect( - xxhashAsU8a('abc', 128) - ).toEqual( - hexToU8a('0x990977adf52cbc440889329981caa9be') - ); - }); - - it('returns a 256-bit value (as specified)', () => { - expect( - xxhashAsU8a('abc', 256) - ).toEqual( - hexToU8a('0x990977adf52cbc440889329981caa9bef7da5770b2b8a05303b75d95360dd62b') - ); - }); -}); diff --git a/packages/util-crypto/src/xxhash/asU8a.ts b/packages/util-crypto/src/xxhash/asU8a.ts deleted file mode 100644 index f863b48d5e..0000000000 --- a/packages/util-crypto/src/xxhash/asU8a.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToU8a } from '@plugnet/util'; -import { isReady, twox } from '@plugnet/wasm-crypto'; - -import xxhash64AsBn from './xxhash64/asBn'; - -/** - * @name xxhashAsU8a - * @summary Creates a xxhash64 u8a from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a `Uint8Array` with the specified `bitLength`. - * @example - *
- * - * ```javascript - * import { xxhashAsU8a } from '@plugnet/util-crypto'; - * - * xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999 - * ``` - */ -export default function xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength: number = 64): Uint8Array { - const iterations = Math.ceil(bitLength / 64); - - if (isReady()) { - return twox(u8aToU8a(data), iterations); - } - - const u8a = new Uint8Array(Math.ceil(bitLength / 8)); - - for (let seed = 0; seed < iterations; seed++) { - u8a.set(xxhash64AsBn(data, seed).toArray('le', 8), seed * 8); - } - - return u8a; -} diff --git a/packages/util-crypto/src/xxhash/index.ts b/packages/util-crypto/src/xxhash/index.ts deleted file mode 100644 index 3d783ec7a0..0000000000 --- a/packages/util-crypto/src/xxhash/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Create xxhash64 values with specified bitlengths - */ - -export { default as xxhashAsHex } from './asHex'; -export { default as xxhashAsU8a } from './asU8a'; diff --git a/packages/util-crypto/src/xxhash/xxhash64/.nodoc b/packages/util-crypto/src/xxhash/xxhash64/.nodoc deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts deleted file mode 100644 index 9d803e4f91..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { xxhash64AsBn } from '.'; - -describe('xxhash64AsBn', () => { - it('creates the correct BN output', () => { - expect( - xxhash64AsBn('abcd', 0xabcd).toString(16) - ).toEqual('e29f70f8b8c96df7'); - }); -}); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asBn.ts b/packages/util-crypto/src/xxhash/xxhash64/asBn.ts deleted file mode 100644 index 9c9ec15883..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asBn.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import xxhash64AsRaw from './asRaw'; - -/** - * @name xxhash64AsBn - * @summary Creates a xxhash BN from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a BN. - * @example - *
- * - * ```javascript - * import { xxhash64AsNumber } from '@plugnet/util-crypto'; - * - * xxhash64AsBn('abcd', 0xabcd)); // => new BN(0xe29f70f8b8c96df7) - * ``` - */ -export default function xxhash64AsBn (data: Buffer | Uint8Array | string, seed: number): BN { - return new BN( - xxhash64AsRaw(data, seed), - 16 - ); -} diff --git a/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts deleted file mode 100644 index 6d9d941f2b..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { xxhash64AsHex } from '.'; - -describe('xxhash64AsHex', () => { - it('creates the correct hex output', () => { - expect( - xxhash64AsHex('abcd', 0xabcd) - ).toEqual('0xe29f70f8b8c96df7'); - }); -}); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asHex.ts b/packages/util-crypto/src/xxhash/xxhash64/asHex.ts deleted file mode 100644 index d4b45b5093..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asHex.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexAddPrefix } from '@plugnet/util'; - -import xxhash64AsRaw from './asRaw'; - -/** - * @name xxhash64AsHex - * @summary Creates a xxhash hex from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a hex string. - * @example - *
- * - * ```javascript - * import { xxhash64AsHex } from '@plugnet/util-crypto'; - * - * xxhash64AsHex('abcd', 0xabcd)); // => 0xe29f70f8b8c96df7 - * ``` - */ -export default function xxhash64AsHex (data: Buffer | Uint8Array | string, seed: number): string { - return hexAddPrefix( - xxhash64AsRaw(data, seed) - ); -} diff --git a/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts deleted file mode 100644 index 94f8d9b229..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { xxhash64AsRaw } from '.'; - -describe('xxhash64AsRaw', () => { - it('creates the correct non-prefixed hex output', () => { - expect( - xxhash64AsRaw('abcd', 0xabcd) - ).toEqual('e29f70f8b8c96df7'); - }); -}); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts b/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts deleted file mode 100644 index 2249ab9fd8..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import xxhash64AsValue from './asValue'; - -/** - * @name xxhash64AsRaw - * @summary Creates a xxhash non-prefixed hex from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a non-prefixed hex string. - * @example - *
- * - * ```javascript - * import { xxhash64AsRaw } from '@plugnet/util-crypto'; - * - * xxhash64AsRaw('abcd', 0xabcd)); // => e29f70f8b8c96df7 - * ``` - */ -export default function xxhash64AsRaw (data: Buffer | Uint8Array | string, seed: number): string { - return xxhash64AsValue(data, seed).toString(16); -} diff --git a/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts deleted file mode 100644 index c0eb0e02a5..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import xxhash64AsValue from './asValue'; - -describe('xxhash64AsValue', () => { - it('creates the correct output (string input)', () => { - expect( - xxhash64AsValue('abcd', 0xabcd).toString(16) - ).toEqual('e29f70f8b8c96df7'); - }); - - it('creates the correct output (Buffer input)', () => { - expect( - xxhash64AsValue(Buffer.from([0x61, 0x62, 0x63, 0x64]), 0xabcd).toString(16) - ).toEqual('e29f70f8b8c96df7'); - }); - - it('creates the correct output (Uint8Array input)', () => { - expect( - xxhash64AsValue(new Uint8Array([0x61, 0x62, 0x63, 0x64]), 0xabcd).toString(16) - ).toEqual('e29f70f8b8c96df7'); - }); -}); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts b/packages/util-crypto/src/xxhash/xxhash64/asValue.ts deleted file mode 100644 index 2ce78380b6..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import xxhashjs from 'xxhashjs'; -import { isBuffer, isString, u8aToBuffer } from '@plugnet/util'; - -/** - * @name xxhash64AsValue - * @summary Creates a hex number from the input. - * @description - * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a hex number - * @example - *
- * - * ```javascript - * import { xxhash64AsValue } from '@plugnet/util-crypto'; - * - * xxhash64AsValue('abcd', 0xabcd)); // => e29f70f8b8c96df7 - * ``` - */ -export default function xxhash64AsValue (data: Buffer | Uint8Array | string, seed: number): number { - if (isBuffer(data) || isString(data)) { - // @ts-ignore Buffer is ArrayBuffer underlying - return xxhashjs.h64(data, seed); - } - - // @ts-ignore conversion works, yields correct result - return xxhashjs.h64( - u8aToBuffer(data), - seed - ) as any; -} diff --git a/packages/util-crypto/src/xxhash/xxhash64/index.ts b/packages/util-crypto/src/xxhash/xxhash64/index.ts deleted file mode 100644 index 1f3842f745..0000000000 --- a/packages/util-crypto/src/xxhash/xxhash64/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2019 @polkadot/util-crypto authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import xxhash64AsBn from './asBn'; -import xxhash64AsHex from './asHex'; -import xxhash64AsRaw from './asRaw'; - -/** - * @summary Create [XXHash](http://cyan4973.github.io/xxHash/) values as BN, hex & number output - */ -export { - xxhash64AsBn, - xxhash64AsHex, - xxhash64AsRaw -}; diff --git a/packages/util/LICENSE b/packages/util/LICENSE deleted file mode 100644 index 0d381b2e97..0000000000 --- a/packages/util/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -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. diff --git a/packages/util/README.md b/packages/util/README.md deleted file mode 100644 index d3265263d5..0000000000 --- a/packages/util/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# @polkadot/util - -Various useful utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. - -## Usage - -Installation - - -``` -yarn add @polkadot/util -``` - -Functions can be imported directly from the package, e.g. - -```js -import { isHex } from '@polkadot/util'; -``` - -## Utilities - -[Utilities](SUMMARY.md) diff --git a/packages/util/package.json b/packages/util/package.json deleted file mode 100644 index 1091c438e1..0000000000 --- a/packages/util/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "@plugnet/util", - "version": "0.76.1", - "description": "A collection of useful utilities for @plugnet", - "main": "index.js", - "keywords": [ - "Plugnet" - ], - "author": "Jaco Greeff ", - "maintainers": [ - "Jaco Greeff " - ], - "contributors": [], - "license": "Apache-2.0", - "engines": { - "node": ">=6.4" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/polkadot-js/common.git" - }, - "bugs": { - "url": "https://github.com/polkadot-js/common/issues" - }, - "homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme", - "dependencies": { - "@babel/runtime": "^7.4.3", - "@types/bn.js": "^4.11.5", - "@types/deasync": "^0.1.0", - "@types/ip-regex": "^3.0.0", - "bn.js": "^4.11.8", - "camelcase": "^5.3.0", - "chalk": "^2.4.2", - "ip-regex": "^4.0.0", - "moment": "^2.24.0" - } -} diff --git a/packages/util/src/array/filter.spec.ts b/packages/util/src/array/filter.spec.ts deleted file mode 100644 index 77a236610d..0000000000 --- a/packages/util/src/array/filter.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { arrayFilter } from '.'; - -describe('filterArray', () => { - it('filters arrays, removing undefined', () => { - expect( - arrayFilter([0, '', null, false, void 0, NaN]) - ).toEqual([0, '', null, false, NaN]); - }); - - it('filters arrays, removing undefined & null (allowNull = false)', () => { - expect( - arrayFilter([0, '', null, false, void 0, NaN], false) - ).toEqual([0, '', false, NaN]); - }); -}); diff --git a/packages/util/src/array/filter.ts b/packages/util/src/array/filter.ts deleted file mode 100644 index 9a95d20cb1..0000000000 --- a/packages/util/src/array/filter.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isNull from '../is/null'; -import isUndefined from '../is/undefined'; - -/** - * @name arrayFilter - * @summary Filters undefined and (optionally) null values from an array - * @description - * Returns a new array with all `undefined` values removed. Optionally, when `allowNulls = false`, it removes the `null` values as well - * @example - *
- * - * ```javascript - * import { arrayFilter } from '@plugnet/util'; - * - * arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, ''] - * arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, ''] - * ``` - */ -export default function arrayFilter (array: Array, allowNulls: boolean = true): Array { - return array.filter((value) => { - return !isUndefined(value) && (allowNulls || !isNull(value)); - }); -} diff --git a/packages/util/src/array/index.ts b/packages/util/src/array/index.ts deleted file mode 100644 index 98a6249cf4..0000000000 --- a/packages/util/src/array/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods that operates on arrays - */ - -export { default as arrayFilter } from './filter'; diff --git a/packages/util/src/assert.spec.ts b/packages/util/src/assert.spec.ts deleted file mode 100644 index 4fecd6724d..0000000000 --- a/packages/util/src/assert.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assert } from '.'; - -describe('assert', () => { - it('should not throw an error when test is true', () => { - expect( - assert(true, 'nothing should be thrown') - ).toEqual(true); - }); - - it('should throw an error when test is not true', () => { - expect( - () => assert(false, 'error thrown') - ).toThrow(/error thrown/); - }); - - it('should throw an error when message: () => string', () => { - expect( - () => assert(false, () => 'message from function') - ).toThrow(/message from function/); - }); - - it('throws a valid constructed ExtError', () => { - try { - assert(false, 'error', -666, { some: 'data' }); - } catch (error) { - expect(error.code).toEqual(-666); - expect(error.data).toEqual({ some: 'data' }); - expect(error.message).toEqual('error'); - } - }); -}); diff --git a/packages/util/src/assert.ts b/packages/util/src/assert.ts deleted file mode 100644 index c14492d15d..0000000000 --- a/packages/util/src/assert.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import ExtError from './ext/error'; -import isFunction from './is/function'; - -type MessageFn = () => string; - -type Falsy = null | undefined | false | 0 | ''; // No NaN type - -/** - * @name assert - * @summary Checks for a valid test, if not ExtError is thrown. - * @description - * Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an ExtError with the supplied `message` and an optional `code` and `data`. When `test` passes, `true` is returned. - * @example - *
- * - * ```javascript - * const { assert } from '@plugnet/util'; - * - * assert(true, 'True should be true'); // true returned - * assert(false, 'False should not be true'); // ExtError thrown - * assert(false, () => 'message'); // ExtError with 'message' - * ``` - */ -export default function assert (test: Falsy | T, message: string | MessageFn, code: number = ExtError.CODES.ASSERT, data?: any): test is T { - if (test) { - return true; - } - - if (isFunction(message)) { - message = message(); - } - - throw new ExtError(message, code, data); -} diff --git a/packages/util/src/assertSingletonPackage.spec.ts b/packages/util/src/assertSingletonPackage.spec.ts deleted file mode 100644 index 9fc763c696..0000000000 --- a/packages/util/src/assertSingletonPackage.spec.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assertSingletonPackage } from '.'; - -describe('assertSingletonPackage', () => { - const NAME = 'assertSingletonPackage'; - - it('should not throw the first time', () => { - expect( - () => assertSingletonPackage(NAME) - ).not.toThrow(); - }); - - it('should throw the second time', () => { - expect( - () => assertSingletonPackage(NAME) - ).toThrow(/Multiple versions of assertSingletonPackage detected/); - }); -}); diff --git a/packages/util/src/assertSingletonPackage.ts b/packages/util/src/assertSingletonPackage.ts deleted file mode 100644 index 1daf03fda1..0000000000 --- a/packages/util/src/assertSingletonPackage.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isUndefined from './is/undefined'; -import assert from './assert'; - -/** - * @name assertSingletonPackage - * @summary Checks that a specific package is only imported once - */ -export default function assertSingletonPackage (name: string): void { - // tslint:disable-next-line - const _global: any = typeof window !== 'undefined' - ? window - : global; - - if (!_global.__polkadotjs) { - _global.__polkadotjs = {}; - } - - assert(isUndefined(_global.__polkadotjs[name]), `Multiple versions of ${name} detected, ensure that there is only version one in your dependency tree`); - - _global.__polkadotjs[name] = true; -} diff --git a/packages/util/src/bn/fromHex.spec.ts b/packages/util/src/bn/fromHex.spec.ts deleted file mode 100644 index cd5db3affd..0000000000 --- a/packages/util/src/bn/fromHex.spec.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isFunction from '../is/function'; - -import { bnFromHex } from '.'; - -describe('bnFromHex', () => { - it('exists as a function', () => { - expect( - isFunction(bnFromHex) - ).toEqual(true); - }); -}); diff --git a/packages/util/src/bn/fromHex.ts b/packages/util/src/bn/fromHex.ts deleted file mode 100644 index 398d3ab9b6..0000000000 --- a/packages/util/src/bn/fromHex.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import bnFromHex from '../hex/toBn'; - -/** - * @name bnFromHex - * @summary Creates a BN.js bignumber object from a hex string. - * @alias hex/toBn - */ -export default bnFromHex; diff --git a/packages/util/src/bn/index.ts b/packages/util/src/bn/index.ts deleted file mode 100644 index 66f723c5d3..0000000000 --- a/packages/util/src/bn/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods to convert to and from `BN` objects - */ - -export { default as bnFromHex } from './fromHex'; -export { default as bnToBn } from './toBn'; -export { default as bnToHex } from './toHex'; -export { default as bnToU8a } from './toU8a'; diff --git a/packages/util/src/bn/toBn.spec.ts b/packages/util/src/bn/toBn.spec.ts deleted file mode 100644 index 194245485b..0000000000 --- a/packages/util/src/bn/toBn.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import { bnToBn } from '.'; - -describe('bnToBn', () => { - it('converts null values to 0x00', () => { - expect( - bnToBn(null) - ).toEqual(new BN(0)); - }); - - it('converts BN values to BN', () => { - expect( - bnToBn(new BN(128)) - ).toEqual(new BN(128)); - }); - - it('converts number values to BN', () => { - expect( - bnToBn(128) - ).toEqual(new BN(128)); - }); -}); diff --git a/packages/util/src/bn/toBn.ts b/packages/util/src/bn/toBn.ts deleted file mode 100644 index 0df72c27fc..0000000000 --- a/packages/util/src/bn/toBn.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -/** - * @name bnToBn - * @summary Creates a BN value from a BN.js bignumber or number input. - * @description - * `null` inputs returns a `0x0` result, BN values returns the value, numnbers returns a BN representation. - * @example - *
- * - * ```javascript - * import BN from 'bn.js'; - * import { bnToBn } from '@plugnet/util'; - * - * bnToBn(0x1234); // => BN(0x1234) - * bnToBn(new BN(0x1234)); // => BN(0x1234) - * ``` - */ -export default function bnToBn (value?: BN | number | null): BN { - if (!value) { - return new BN(0); - } - - return BN.isBN(value) - ? value - : new BN(value); -} diff --git a/packages/util/src/bn/toHex.spec.ts b/packages/util/src/bn/toHex.spec.ts deleted file mode 100644 index a34bc00dfa..0000000000 --- a/packages/util/src/bn/toHex.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import { bnToHex } from '.'; - -describe('bnToHex', () => { - it('converts null values to 0x00', () => { - expect( - bnToHex(null) - ).toBe('0x00'); - }); - - it('converts BN values to a prefixed hex representation', () => { - expect( - bnToHex(new BN(128)) - ).toBe('0x80'); - }); - - it('converts BN values to a prefixed hex representation (bitLength)', () => { - expect( - bnToHex(new BN(128), 16) - ).toBe('0x0080'); - }); - - it('converts BN values to a prefixed hex representation (LE)', () => { - expect( - bnToHex(new BN(128), { bitLength: 16, isLe: true }) - ).toBe('0x8000'); - }); - - it('handles negative numbers', () => { - expect( - bnToHex(new BN(-1234), { isNegative: true }) - ).toBe('0xfb2e'); - }); - - it('handles negative numbers (with bitLength)', () => { - expect( - bnToHex(new BN(-1234), { bitLength: 32, isNegative: true }) - ).toBe('0xfffffb2e'); - }); - - it('handles backwards compatibility', () => { - expect( - bnToHex(new BN(1234), 32) - ).toBe( - bnToHex(new BN(1234), { bitLength: 32 }) - ); - }); -}); diff --git a/packages/util/src/bn/toHex.ts b/packages/util/src/bn/toHex.ts deleted file mode 100644 index 0b610299f0..0000000000 --- a/packages/util/src/bn/toHex.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import isNumber from '../is/number'; -import bnToU8a from './toU8a'; -import { ToBnOptions } from '../types'; -import { u8aToHex } from '../u8a'; - -const ZERO_STR = '0x00'; - -interface Options extends ToBnOptions { - bitLength?: number; -} - -/** - * @name bnToHex - * @summary Creates a hex value from a BN.js bignumber object. - * @description - * `null` inputs returns a `0x` result, BN values return the actual value as a `0x` prefixed hex value. Anything that is not a BN object throws an error. With `bitLength` set, it fixes the number to the specified length. - * @example - *
- * - * ```javascript - * import BN from 'bn.js'; - * import { bnToHex } from '@plugnet/util'; - * - * bnToHex(new BN(0x123456)); // => '0x123456' - * ``` - */ -export default function bnToHex ( - value?: BN | number | null, - options: number | Options = { bitLength: -1, isLe: false, isNegative: false } -): string { - if (!value) { - return ZERO_STR; - } - - const _options = { - isLe: false, - isNegative: false, - // Backwards-compatibility - ...(isNumber(options) ? { bitLength: options } : options) - }; - - return u8aToHex(bnToU8a(value, _options)); -} diff --git a/packages/util/src/bn/toU8a.spec.ts b/packages/util/src/bn/toU8a.spec.ts deleted file mode 100644 index 998479ef55..0000000000 --- a/packages/util/src/bn/toU8a.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import { bnToU8a } from '.'; - -describe('bnToU8a', () => { - it('converts null values to 0x00', () => { - expect( - bnToU8a(null, -1, false) - ).toEqual(new Uint8Array([])); - }); - - it('converts null values to 0x00000000 (bitLength)', () => { - expect( - bnToU8a(null, 32, false) - ).toEqual(new Uint8Array([0, 0, 0, 0])); - }); - - it('converts BN values to a prefixed hex representation', () => { - expect( - bnToU8a(new BN(0x123456), -1, false) - ).toEqual(new Uint8Array([0x12, 0x34, 0x56])); - }); - - it('converts BN values to a prefixed hex representation (bitLength)', () => { - expect( - bnToU8a(new BN(0x123456), 32, false) - ).toEqual(new Uint8Array([0x00, 0x12, 0x34, 0x56])); - }); - - it('converts using little endian (as set)', () => { - expect( - bnToU8a(new BN(0x123456), 32, true) - ).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00])); - }); - - it('converts negative numbers', () => { - expect( - bnToU8a(new BN(-1234), { isNegative: true }) - ).toEqual(new Uint8Array([46, 251])); - }); - - it('converts negative numbers (BE)', () => { - expect( - bnToU8a(new BN(-1234), { isNegative: true, isLe: false }) - ).toEqual(new Uint8Array([251, 46])); - }); - - it('converts negative numbers (bitLength)', () => { - expect( - bnToU8a(new BN(-1234), { isNegative: true, bitLength: 32 }) - ).toEqual(new Uint8Array([46, 251, 255, 255])); - }); - - it('handles backwards compatibility', () => { - expect( - bnToU8a(new BN(1234), 32, false) - ).toEqual( - bnToU8a(new BN(1234), { bitLength: 32, isLe: false }) - ); - }); -}); diff --git a/packages/util/src/bn/toU8a.ts b/packages/util/src/bn/toU8a.ts deleted file mode 100644 index 8bf9612995..0000000000 --- a/packages/util/src/bn/toU8a.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import isNumber from '../is/number'; -import bnToBn from './toBn'; -import { ToBnOptions } from '../types'; - -interface Options extends ToBnOptions { - bitLength?: number; -} - -/** - * @name bnToU8a - * @summary Creates a Uint8Array object from a BN. - * @description - * `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set. - * @example - *
- * - * ```javascript - * import { bnToU8a } from '@plugnet/util'; - * - * bnToU8a(new BN(0x1234)); // => [0x12, 0x34] - * ``` - */ -export default function bnToU8a (value: BN | number | null, options?: Options): Uint8Array; -export default function bnToU8a (value: BN | number | null, bitLength?: number, isLe?: boolean): Uint8Array; -export default function bnToU8a ( - value: BN | number | null, - arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, - arg2?: boolean -): Uint8Array { - const _options: Options = { - isLe: true, - isNegative: false, - bitLength: -1, - ...isNumber(arg1) ? { bitLength: arg1, isLe: arg2 } : arg1 - }; - - const valueBn = bnToBn(value); - let byteLength = _options.bitLength === -1 - ? Math.ceil(valueBn.bitLength() / 8) - : Math.ceil(_options.bitLength! / 8); - - if (!value) { - return _options.bitLength === -1 - ? new Uint8Array([]) - : new Uint8Array(byteLength); - } - - const output = new Uint8Array(byteLength); - const bn = _options.isNegative ? valueBn.toTwos(byteLength * 8) : valueBn; - - output.set( - bn.toArray(_options.isLe ? 'le' : 'be', byteLength), - 0 - ); - - return output; -} diff --git a/packages/util/src/buffer/index.ts b/packages/util/src/buffer/index.ts deleted file mode 100644 index 69de6a88d5..0000000000 --- a/packages/util/src/buffer/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods to convert to and from `Buffer` objects - */ - -export { default as bufferToU8a } from './toU8a'; diff --git a/packages/util/src/buffer/toU8a.spec.ts b/packages/util/src/buffer/toU8a.spec.ts deleted file mode 100644 index 1f6f991e1b..0000000000 --- a/packages/util/src/buffer/toU8a.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { bufferToU8a } from '.'; - -describe('bufferToU8a', () => { - it('returns an empty buffer when null provided', () => { - expect( - bufferToU8a(null) - ).toEqual(new Uint8Array([])); - }); - - it('returns a Uint8Buffer with the correct values', () => { - expect( - bufferToU8a(Buffer.from([128, 0, 10])) - ).toEqual(new Uint8Array([128, 0, 10])); - }); -}); diff --git a/packages/util/src/buffer/toU8a.ts b/packages/util/src/buffer/toU8a.ts deleted file mode 100644 index 494fcc3f59..0000000000 --- a/packages/util/src/buffer/toU8a.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name bufferToU8a - * @summary Creates a Uint8Array value from a Buffer object. - * @description - * `null` inputs returns an empty result, `Buffer` values return the actual value as a `Uint8Array`. Anything that is not a `Buffer` object throws an error. - * @example - *
- * - * ```javascript - * import { bufferToU8a } from '@plugnet/util'; - * - * bufferToU8a(Buffer.from([1, 2, 3])); - * ``` - */ -export default function bufferToU8a (buffer?: Buffer | number[] | null): Uint8Array { - if (!buffer) { - return new Uint8Array([]); - } - - return new Uint8Array(buffer); -} diff --git a/packages/util/src/compact/addLength.spec.ts b/packages/util/src/compact/addLength.spec.ts deleted file mode 100644 index 2d3f5ebd4a..0000000000 --- a/packages/util/src/compact/addLength.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import compactAddLength from './addLength'; - -describe('compactAddLength', () => { - it('correctly adds the length prefix', () => { - expect( - compactAddLength(Uint8Array.from([12, 13])) - ).toEqual(Uint8Array.from([2 << 2, 12, 13])); - }); -}); diff --git a/packages/util/src/compact/addLength.ts b/packages/util/src/compact/addLength.ts deleted file mode 100644 index 1bba4d07bd..0000000000 --- a/packages/util/src/compact/addLength.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aConcat } from '../u8a'; -import compactToU8a from './toU8a'; - -/** - * @name compactAddLength - * @description Adds a length prefix to the input value - * @example - *
- * - * ```javascript - * import { compactAddLength } from '@plugnet/util'; - * - * console.log(compactAddLength(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))); // Uint8Array([4 << 2, 0xde, 0xad, 0xbe, 0xef]) - * ``` - */ -export default function compactAddLength (input: Uint8Array): Uint8Array { - return u8aConcat( - compactToU8a(input.length), - input - ); -} diff --git a/packages/util/src/compact/defaults.ts b/packages/util/src/compact/defaults.ts deleted file mode 100644 index 00c4df0e64..0000000000 --- a/packages/util/src/compact/defaults.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { BitLength } from './types'; - -export const DEFAULT_BITLENGTH: BitLength = 32; diff --git a/packages/util/src/compact/fromU8a.spec.ts b/packages/util/src/compact/fromU8a.spec.ts deleted file mode 100644 index 52d264252e..0000000000 --- a/packages/util/src/compact/fromU8a.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import hexToU8a from '../hex/toU8a'; -import compactFromU8a from './fromU8a'; - -describe('compactFromU8a', () => { - it('decoded u8 value', () => { - expect( - compactFromU8a(new Uint8Array([0b11111100])) - ).toEqual([1, new BN(63)]); - }); - - it('decodes from same u16 encoded value', () => { - expect( - compactFromU8a(new Uint8Array([0b11111101, 0b00000111]), 32) - ).toEqual([2, new BN(511)]); - }); - - it('decodes from same u32 encoded value (short)', () => { - expect( - compactFromU8a(new Uint8Array([254, 255, 3, 0]), 32) - ).toEqual([4, new BN(0xffff)]); - }); - - it('decodes from same u32 encoded value (full)', () => { - expect( - compactFromU8a(new Uint8Array([3, 249, 255, 255, 255]), 32) - ).toEqual([5, new BN(0xfffffff9)]); - }); - - it('decodes from same u32 as u64 encoded value (full, default)', () => { - expect( - compactFromU8a(new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]), 64) - ).toEqual([5, new BN(0xfffffff9)]); - }); - - it('decodes an actual value', () => { - expect( - compactFromU8a( - hexToU8a('0x0b00407a10f35a') - ) - ).toEqual([7, new BN('5af3107a4000', 16)]); - }); -}); diff --git a/packages/util/src/compact/fromU8a.ts b/packages/util/src/compact/fromU8a.ts deleted file mode 100644 index 73c69cd22c..0000000000 --- a/packages/util/src/compact/fromU8a.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { BitLength } from './types'; - -import BN from 'bn.js'; - -import { u8aToBn, u8aToU8a } from '../u8a'; -import { DEFAULT_BITLENGTH } from './defaults'; - -/** - * @name compactFromU8a - * @description Retrievs the offset and encoded length from a compact-prefixed value - * @example - *
- * - * ```javascript - * import { compactFromU8a } from '@plugnet/util'; - * - * const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]), 32)); - * - * console.log('value offset=', offset, 'length=', length); // 4, 0xffff - * ``` - */ -export default function compactFromU8a (_input: Uint8Array | string, bitLength: BitLength = DEFAULT_BITLENGTH): [number, BN] { - const input = u8aToU8a(_input); - const flag = input[0] & 0b11; - - if (flag === 0b00) { - return [1, new BN(input[0]).shrn(2)]; - } else if (flag === 0b01) { - return [2, u8aToBn(input.slice(0, 2), true).shrn(2)]; - } else if (flag === 0b10) { - return [4, u8aToBn(input.slice(0, 4), true).shrn(2)]; - } - - const length = new BN(input[0]) - .shrn(2) // clear flag - .addn(4) // add 4 for base length - .toNumber(); - const offset = 1 + length; - - return [offset, u8aToBn(input.subarray(1, offset), true)]; -} diff --git a/packages/util/src/compact/index.ts b/packages/util/src/compact/index.ts deleted file mode 100644 index 6f56f95cd8..0000000000 --- a/packages/util/src/compact/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @description - * Encoding and decoding of parity-codec compact numbers. The codec is created - * to take up the least amount of space for a specific number. It performs the - * same function as Length, however differs in that it uses a variable number of - * bytes to do the actual encoding. From the Rust implementation for compact - * encoding: - * - * 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00 - * (0 ... 2**6 - 1) (u8) - * xx xx xx 00 - * (2**6 ... 2**14 - 1) (u8, u16) low LH high - * yL yL yL 01 / yH yH yH yL - * (2**14 ... 2**30 - 1) (u16, u32) low LMMH high - * zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM - * (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded - * nn nn nn 11 [ / zz zz zz zz ]{4 + n} - * - * Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key. - */ - -export { default as compactAddLength } from './addLength'; -export { default as compactStripLength } from './stripLength'; -export { default as compactFromU8a } from './fromU8a'; -export { default as compactToU8a } from './toU8a'; diff --git a/packages/util/src/compact/stripLength.spec.ts b/packages/util/src/compact/stripLength.spec.ts deleted file mode 100644 index d00c8ed7f7..0000000000 --- a/packages/util/src/compact/stripLength.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import compactStripLength from './stripLength'; - -describe('compactStripLength', () => { - it('correctly removes the length prefix', () => { - expect( - compactStripLength(Uint8Array.from([2 << 2, 12, 13])) - ).toEqual([ - 3, - Uint8Array.from([12, 13]) - ]); - }); -}); diff --git a/packages/util/src/compact/stripLength.ts b/packages/util/src/compact/stripLength.ts deleted file mode 100644 index 85bfeb0ebb..0000000000 --- a/packages/util/src/compact/stripLength.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { BitLength } from './types'; - -import { DEFAULT_BITLENGTH } from './defaults'; -import compactFromU8a from './fromU8a'; - -/** - * @name compactStripLength - * @description Removes the length prefix, returning both the total length (including the value + compact encoding) and the decoded value with the correct length - * @example - *
- * - * ```javascript - * import { compactStripLength } from '@plugnet/util'; - * - * console.log(compactStripLength(new Uint8Array([2 << 2, 0xde, 0xad]))); // [2, Uint8Array[0xde, 0xad]] - * ``` - */ -export default function compactStripLength (input: Uint8Array, bitLength: BitLength = DEFAULT_BITLENGTH): [number, Uint8Array] { - const [offset, length] = compactFromU8a(input, bitLength); - const total = offset + length.toNumber(); - - return [ - total, - input.subarray(offset, total) - ]; -} diff --git a/packages/util/src/compact/toU8a.spec.ts b/packages/util/src/compact/toU8a.spec.ts deleted file mode 100644 index 3e9b26f2a3..0000000000 --- a/packages/util/src/compact/toU8a.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import compactToU8a from './toU8a'; - -describe('encode', () => { - it('encodes short u8', () => { - expect( - compactToU8a(18) - ).toEqual( - new Uint8Array([18 << 2]) - ); - }); - - it('encodes max u8 values', () => { - expect( - compactToU8a(new BN(63)) - ).toEqual( - new Uint8Array([0b11111100]) - ); - }); - - it('encodes basic u16 value', () => { - expect( - compactToU8a(511) - ).toEqual( - new Uint8Array([0b11111101, 0b00000111]) - ); - }); - - it('encodes basic u16 (not at edge)', () => { - expect( - compactToU8a(111) - ).toEqual( - new Uint8Array([0xbd, 0x01]) - ); - }); - - it('encodes basic u32 values (short)', () => { - expect( - compactToU8a(0xffff) - ).toEqual( - new Uint8Array([254, 255, 3, 0]) - ); - }); - - it('encodes basic u32 values (full)', () => { - expect( - compactToU8a(0xfffffff9) - ).toEqual( - new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]) - ); - }); - - it('encodes a large value', () => { - expect( - compactToU8a( - new BN('00005af3107a4000', 16) - ) - ).toEqual( - new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a]) - ); - }); - - describe('from Rust', () => { - // Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs - const testCases = [ - { value: new BN('0'), expected: '00' }, - { value: new BN('63'), expected: 'fc' }, - { value: new BN('64'), expected: '01 01' }, - { value: new BN('16383'), expected: 'fd ff' }, - { value: new BN('16384'), expected: '02 00 01 00' }, - { value: new BN('1073741823'), expected: 'fe ff ff ff' }, - { value: new BN('1073741824'), expected: '03 00 00 00 40' }, - { value: new BN(`${1}${'0'.repeat(32)}`, 2).subn(1), expected: '03 ff ff ff ff' }, - { value: new BN(`${1}${'0'.repeat(32)}`, 2), expected: '07 00 00 00 00 01' }, - { value: new BN(`${1}${'0'.repeat(40)}`, 2), expected: '0b 00 00 00 00 00 01' }, - { value: new BN(`${1}${'0'.repeat(48)}`, 2), expected: '0f 00 00 00 00 00 00 01' }, - { value: new BN(`${1}${'0'.repeat(56)}`, 2).subn(1), expected: '0f ff ff ff ff ff ff ff' }, - { value: new BN(`${1}${'0'.repeat(56)}`, 2), expected: '13 00 00 00 00 00 00 00 01' }, - { value: new BN(`${1}${'0'.repeat(64)}`, 2).subn(1), expected: '13 ff ff ff ff ff ff ff ff' } - ]; - - function testEncode (value: BN, expected: string) { - it(`encodes ${value.toString()}`, () => { - expect( - compactToU8a(value) - ).toEqual( - Uint8Array.from( - expected.split(' ').map(s => parseInt(s, 16)) - ) - ); - }); - } - - testCases.forEach((({ value, expected }) => testEncode(value, expected))); - }); - -}); diff --git a/packages/util/src/compact/toU8a.ts b/packages/util/src/compact/toU8a.ts deleted file mode 100644 index 4fd564a6db..0000000000 --- a/packages/util/src/compact/toU8a.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import assert from '../assert'; -import { bnToBn, bnToU8a } from '../bn'; -import { u8aConcat } from '../u8a'; - -const MAX_U8 = new BN(2).pow(new BN(8 - 2)).subn(1); -const MAX_U16 = new BN(2).pow(new BN(16 - 2)).subn(1); -const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1); - -/** - * @name compactToU8a - * @description Encodes a number into a compact representation - * @example - *
- * - * ```javascript - * import { compactToU8a } from '@plugnet/util'; - * - * console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111]) - * ``` - */ -export default function compactToU8a (_value: BN | number): Uint8Array { - const value = bnToBn(_value); - - if (value.lte(MAX_U8)) { - return new Uint8Array([value.toNumber() << 2]); - } else if (value.lte(MAX_U16)) { - return bnToU8a(value.shln(2).addn(0b01), 16, true); - } else if (value.lte(MAX_U32)) { - return bnToU8a(value.shln(2).addn(0b10), 32, true); - } - - const u8a = bnToU8a(value); - let length = u8a.length; - - // adjust to the minimum number of bytes - while (u8a[length - 1] === 0) { - length--; - } - - assert(length >= 4, 'Previous tests match anyting less than 2^30; qed'); - - return u8aConcat( - new Uint8Array([ - // substract 4 as minimum (also catered for in decoding) - ((length - 4) << 2) + 0b11 - ]), - u8a.subarray(0, length) - ); -} diff --git a/packages/util/src/compact/types.ts b/packages/util/src/compact/types.ts deleted file mode 100644 index 8d232ed9ca..0000000000 --- a/packages/util/src/compact/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export type BitLength = 8 | 16 | 32 | 64 | 128 | 256; diff --git a/packages/util/src/ext/error.spec.ts b/packages/util/src/ext/error.spec.ts deleted file mode 100644 index e2402025fa..0000000000 --- a/packages/util/src/ext/error.spec.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isError from '../is/error'; -import { ExtError } from '.'; - -describe('ExtError', () => { - describe('constructor', () => { - it('constructs an Error that is still an Error', () => { - expect( - isError( - new ExtError() - ) - ).toEqual(true); - }); - }); - - describe('static', () => { - it('exposes the .CODES as a static', () => { - expect( - Object.keys(ExtError.CODES) - ).not.toEqual(0); - }); - }); - - describe('constructor properties', () => { - it('sets the .message property', () => { - expect( - new ExtError('test message').message - ).toEqual('test message'); - }); - - it("sets the .message to '' when not set", () => { - expect( - new ExtError().message - ).toEqual(''); - }); - - it('sets the .code property', () => { - expect( - new ExtError('test message', 1234).code - ).toEqual(1234); - }); - - it('sets the .code to UKNOWN when not set', () => { - expect( - new ExtError('test message').code - ).toEqual(ExtError.CODES.UNKNOWN); - }); - - it('sets the .data property', () => { - const data = { some: { value: 'here' } }; - - expect( - new ExtError('test message', 1234, data).data - ).toEqual(data); - }); - }); - - describe('stack traces', () => { - let captureStackTrace: any; - - beforeEach(() => { - captureStackTrace = Error.captureStackTrace; - - Error.captureStackTrace = function (error) { - Object.defineProperty(error, 'stack', { - configurable: true, - get: function getStack () { - const value = 'some stack returned'; - - Object.defineProperty(this, 'stack', { value }); - - return value; - } - }); - }; - }); - - afterEach(() => { - Error.captureStackTrace = captureStackTrace; - }); - - it('captures via captureStackTrace when available', () => { - expect( - new ExtError().stack - ).toEqual('some stack returned'); - }); - - it('captures via stack when captureStackTrace not available', () => { - Error.captureStackTrace = null as any; // grrr - - expect( - new ExtError().stack.length - ).not.toEqual(0); - }); - }); -}); diff --git a/packages/util/src/ext/error.ts b/packages/util/src/ext/error.ts deleted file mode 100644 index 75da047725..0000000000 --- a/packages/util/src/ext/error.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { ExtErrorInterface } from '../types'; - -import isFunction from '../is/function'; - -const UNKNOWN = -99999; - -function extend (that: any, name: string, value: any): void { - Object.defineProperty(that, name, { - configurable: true, - enumerable: false, - value - }); -} - -/** - * @name ExtError - * @summary Extension to the basic JS Error. - * @description - * The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object. - * @example - *
- * - * ```javascript - * const { ExtError } from '@plugnet/util'); - * - * throw new ExtError('some message', ExtError.CODES.METHOD_NOT_FOUND); // => error.code = -32601 - * ``` - */ -export default class ExtError extends Error implements ExtErrorInterface { - // @ts-ignore we are assigning it via extend - code: number; - // @ts-ignore we are assigning it via extend - data: any; - // @ts-ignore we are assigning it via extend - message: string; - // @ts-ignore we are assigning it via extend - name: string; - // @ts-ignore we are assigning it via extend - stack: string; - - constructor (message: string = '', code: number = UNKNOWN, data?: any) { - super(); - - extend(this, 'message', String(message)); - extend(this, 'name', this.constructor.name); - extend(this, 'data', data); - extend(this, 'code', code); - - if (isFunction(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } else { - extend(this, 'stack', (new Error(message)).stack); - } - } - - static CODES = { - ASSERT: -90009, - UNKNOWN, - INVALID_JSONRPC: -99998, - METHOD_NOT_FOUND: -32601 // Rust client - }; -} diff --git a/packages/util/src/ext/index.ts b/packages/util/src/ext/index.ts deleted file mode 100644 index f73ae68c8f..0000000000 --- a/packages/util/src/ext/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Extensions to basic classes - */ - -export { default as ExtError } from './error'; diff --git a/packages/util/src/format/formatBalance.spec.ts b/packages/util/src/format/formatBalance.spec.ts deleted file mode 100644 index 14a0a3dcbb..0000000000 --- a/packages/util/src/format/formatBalance.spec.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import formatBalance from './formatBalance'; - -describe('formatBalance', () => { - const TESTVAL = new BN('123456789000'); - - it('formats empty to 0', () => { - expect(formatBalance()).toEqual('0'); - expect(formatBalance('0')).toEqual('0'); - }); - - it('formats 123,456,789,000 (decimals=15)', () => { - expect( - formatBalance(TESTVAL, true, 15) - ).toEqual('123.456µ Unit'); - }); - - it('formats 123,456,789,000 (decimals=12)', () => { - expect( - formatBalance(TESTVAL, true, 12) - ).toEqual('123.456m Unit'); - }); - - it('formats 123,456,789,000 (decimals=12, no SI)', () => { - expect( - formatBalance(TESTVAL, false, 12) - ).toEqual('123.456'); - }); - - it('formats 123,456,789,000 (decimals=9)', () => { - expect( - formatBalance(TESTVAL, true, 9) - ).toEqual('123.456 Unit'); - }); - - it('formats 123,456,789,000 (decimals=6)', () => { - expect( - formatBalance(TESTVAL, true, 6) - ).toEqual('123.456k Unit'); - }); - - it('formats 123,456,789,000 * 10 (decimals=12)', () => { - expect( - formatBalance(TESTVAL.muln(10), true, 12) - ).toEqual('1.234 Unit'); - }); - - it('formats 123,456,789,000 * 100 (decimals=12)', () => { - expect( - formatBalance(TESTVAL.muln(100), true, 12) - ).toEqual('12.345 Unit'); - }); - - it('formats 123,456,789,000 * 1000 (decimals=12)', () => { - expect( - formatBalance(TESTVAL.muln(1000), true, 12) - ).toEqual('123.456 Unit'); - }); - - describe('findSi', () => { - it('finds the SI value', () => { - expect( - formatBalance.findSi('k') - ).toEqual({ power: 3, value: 'k', text: 'Kilo' }); - }); - - it('returns default on not found', () => { - expect( - formatBalance.findSi('blah') - ).toEqual({ power: 0, value: '-', text: 'Unit' }); - }); - }); - - describe('defaults', () => { - it('returns defaults', () => { - expect(formatBalance.getDefaults()).toEqual({ - decimals: 0, - unit: 'Unit' - }); - }); - - it('formats 123,456,789,000 (defaultDecimals=12)', () => { - formatBalance.setDefaults({ decimals: 12 }); - - expect( - formatBalance(TESTVAL) - ).toEqual('123.456m Unit'); - }); - - it('formats 123,456,789,000 (defaultUnit=TEST)', () => { - formatBalance.setDefaults({ unit: 'TEST' }); - - expect( - formatBalance(TESTVAL) - ).toEqual('123.456m TEST'); - }); - }); - - it('returns options for dropdown', () => { - formatBalance.setDefaults({ decimals: 0, unit: 'TEST' }); - - expect( - formatBalance.getOptions() - ).toEqual([ - { power: 0, value: '-', text: 'TEST' }, - { power: 3, value: 'k', text: 'Kilo' }, - { power: 6, value: 'M', text: 'Mega' }, - { power: 9, value: 'G', text: 'Giga' }, - { power: 12, value: 'T', text: 'Tera' }, - { power: 15, value: 'P', text: 'Peta' }, - { power: 18, value: 'E', text: 'Exa' }, - { power: 21, value: 'Z', text: 'Zeta' }, - { power: 24, value: 'Y', text: 'Yotta' } - ]); - }); -}); diff --git a/packages/util/src/format/formatBalance.ts b/packages/util/src/format/formatBalance.ts deleted file mode 100644 index 7b4b4d4979..0000000000 --- a/packages/util/src/format/formatBalance.ts +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import isUndefined from '../is/undefined'; -import { SI, SI_MID, SiDef, calcSi, findSi } from './si'; -import formatDecimal from './formatDecimal'; - -type Defaults = { - decimals: number, - unit: string -}; - -interface BalanceFormatter { - (input?: number | string | BN, withSi?: boolean, decimals?: number): string; - calcSi (text: string, decimals?: number): SiDef; - findSi (type: string): SiDef; - getDefaults (): Defaults; - getOptions (decimals?: number): Array; - setDefaults (defaults: Partial): void; -} - -const DEFAULT_DECIMALS = 0; -const DEFAULT_UNIT = SI[SI_MID].text; - -let defaultDecimals = DEFAULT_DECIMALS; -let defaultUnit = DEFAULT_UNIT; - -// Formats a string/number with . notation -function _formatBalance (input?: number | string | BN, withSi: boolean = true, decimals: number = defaultDecimals): string { - const text = (input || '').toString(); - - if (text.length === 0 || text === '0') { - return '0'; - } - - // NOTE We start at midpoint (8) minus 1 - this means that values display as - // 123.456 instead of 0.123k (so always 6 relevant). Additionally we us ceil - // so there are at most 3 decimal before the decimal seperator - const si = calcSi(text, decimals); - const mid = text.length - (decimals + si.power); - const prefix = text.substr(0, mid); - const postfix = `${text.substr(mid)}000`.substr(0, 3); - const units = withSi - ? ( - si.value === '-' - ? ` ${si.text}` - : `${si.value} ${SI[SI_MID].text}` - ) - : ''; - - return `${formatDecimal(prefix || '0')}.${postfix}${units}`; -} - -const formatBalance = _formatBalance as BalanceFormatter; - -formatBalance.calcSi = (text: string, decimals: number = defaultDecimals): SiDef => - calcSi(text, decimals); -formatBalance.findSi = findSi; - -formatBalance.getDefaults = (): Defaults => { - return { - decimals: defaultDecimals, - unit: defaultUnit - }; -}; - -// get allowable options to display in a dropdown -formatBalance.getOptions = (decimals: number = defaultDecimals): Array => { - return SI.filter(({ power }) => - power < 0 - ? (decimals + power) >= 0 - : true - ); -}; - -// Sets the default decimals to use for formatting (ui-wide) -formatBalance.setDefaults = ({ decimals, unit }: Partial): void => { - defaultDecimals = isUndefined(decimals) ? defaultDecimals : decimals; - defaultUnit = isUndefined(unit) ? defaultUnit : unit; - - SI[SI_MID].text = defaultUnit; -}; - -export default formatBalance; diff --git a/packages/util/src/format/formatDecimal.spec.ts b/packages/util/src/format/formatDecimal.spec.ts deleted file mode 100644 index 49cbb207c7..0000000000 --- a/packages/util/src/format/formatDecimal.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import formatDecimal from './formatDecimal'; - -describe('formatDecimal', () => { - it('formats decimals in number groupings', () => { - expect(formatDecimal('12345')).toEqual('12,345'); - }); - - it('formats decimal-only in number groupings', () => { - expect(formatDecimal('test6789')).toEqual('6,789'); - }); - - it('returns input for non-decimal', () => { - expect(formatDecimal('test')).toEqual('test'); - }); -}); diff --git a/packages/util/src/format/formatDecimal.ts b/packages/util/src/format/formatDecimal.ts deleted file mode 100644 index 097c21462c..0000000000 --- a/packages/util/src/format/formatDecimal.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g'); - -export default function formatDecimal (value: string): string { - const matched = value.match(NUMBER_REGEX); - - return matched - ? matched.join(',') - : value; -} diff --git a/packages/util/src/format/formatElapsed.spec.ts b/packages/util/src/format/formatElapsed.spec.ts deleted file mode 100644 index 8ec261b750..0000000000 --- a/packages/util/src/format/formatElapsed.spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Compact } from './types'; - -import BN from 'bn.js'; - -import formatElapsed from './formatElapsed'; - -describe('formatElapsed', () => { - const start = 12345678; - const now = new Date(12345678); - - it('formats a Date', () => { - expect( - formatElapsed(now, new Date(start + 9700)) - ).toEqual('9.7s'); - }); - - it('formats a BN', () => { - expect( - formatElapsed(now, new BN(start + 42700)) - ).toEqual('42s'); - }); - - it('formats a Compact', () => { - expect( - formatElapsed(now, { unwrap: () => new BN(start + (5.3 * 60000)) } as Compact) - ).toEqual('5m'); - }); - - it('formats a number', () => { - expect( - formatElapsed(now, start + (42 * 60 * 60000)) - ).toEqual('42h'); - }); - - it('formats defaults', () => { - expect( - formatElapsed() - ).toEqual('0.0s'); - }); -}); diff --git a/packages/util/src/format/formatElapsed.ts b/packages/util/src/format/formatElapsed.ts deleted file mode 100644 index 18ff900f22..0000000000 --- a/packages/util/src/format/formatElapsed.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017-2019 @polkadot/ui-util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Compact } from './types'; - -import BN from 'bn.js'; - -function getValue (value?: BN | Compact | Date | number | null): number { - if (value) { - if ((value as any).unwrap) { - return getValue((value as Compact).unwrap()); - } else if (value instanceof Date) { - return getValue(value.getTime()); - } else if (value instanceof BN) { - return getValue(value.toNumber()); - } - } - - return (value as number) || 0; -} - -export default function formatElapsed (now?: Date | null, value?: BN | Compact | Date | number | null): string { - const tsNow = (now && now.getTime()) || 0; - const tsValue = getValue(value); - let display = '0.0s'; - - if (tsNow && tsValue) { - const elapsed = Math.max(Math.abs(tsNow - tsValue), 0) / 1000; - - if (elapsed < 15) { - display = `${elapsed.toFixed(1)}s`; - } else if (elapsed < 60) { - display = `${elapsed | 0}s`; - } else if (elapsed < 3600) { - display = `${elapsed / 60 | 0}m`; - } else { - display = `${elapsed / 3600 | 0}h`; - } - } - - return display; -} diff --git a/packages/util/src/format/formatNumber.ts b/packages/util/src/format/formatNumber.ts deleted file mode 100644 index 7100219036..0000000000 --- a/packages/util/src/format/formatNumber.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Compact } from './types'; - -import BN from 'bn.js'; - -import bnToBn from '../bn/toBn'; -import formatDecimal from './formatDecimal'; - -export default function formatNumber (_value?: Compact | BN | number | null): string { - if (!_value) { - return '0'; - } - - const value = (_value as any).toBn - ? (_value as Compact).toBn() - : bnToBn(_value as BN); - - return formatDecimal(value.toString()); -} diff --git a/packages/util/src/format/index.ts b/packages/util/src/format/index.ts deleted file mode 100644 index 222e553f8c..0000000000 --- a/packages/util/src/format/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export { default as formatBalance } from './formatBalance'; -export { default as formatDecimal } from './formatDecimal'; -export { default as formatElapsed } from './formatElapsed'; -export { default as formatNumber } from './formatNumber'; -export { calcSi, findSi } from './si'; diff --git a/packages/util/src/format/si.ts b/packages/util/src/format/si.ts deleted file mode 100644 index 0f0b4763f9..0000000000 --- a/packages/util/src/format/si.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export type SiDef = { - power: number, - text: string, - value: string -}; - -export const SI_MID = 8; - -export const SI: Array = [ - { power: -24, value: 'y', text: 'yocto' }, - { power: -21, value: 'z', text: 'zepto' }, - { power: -18, value: 'a', text: 'atto' }, - { power: -15, value: 'f', text: 'femto' }, - { power: -12, value: 'p', text: 'pico' }, - { power: -9, value: 'n', text: 'nano' }, - { power: -6, value: 'µ', text: 'micro' }, - { power: -3, value: 'm', text: 'milli' }, - { power: 0, value: '-', text: 'Unit' }, // position 8 - { power: 3, value: 'k', text: 'Kilo' }, - { power: 6, value: 'M', text: 'Mega' }, - { power: 9, value: 'G', text: 'Giga' }, - { power: 12, value: 'T', text: 'Tera' }, - { power: 15, value: 'P', text: 'Peta' }, - { power: 18, value: 'E', text: 'Exa' }, - { power: 21, value: 'Z', text: 'Zeta' }, - { power: 24, value: 'Y', text: 'Yotta' } -]; - -export function calcSi (text: string, decimals: number): SiDef { - return SI[(SI_MID - 1) + Math.ceil((text.length - decimals) / 3)] || SI[SI.length - 1]; -} - -// Given a SI type (e.g. k, m, Y) find the SI definition -export function findSi (type: string): SiDef { - // use a loop here, better RN support (which doesn't have [].find) - for (let i = 0; i < SI.length; i++) { - if (SI[i].value === type) { - return SI[i]; - } - } - - return SI[SI_MID]; -} diff --git a/packages/util/src/format/types.ts b/packages/util/src/format/types.ts deleted file mode 100644 index 3fc6b4a1ae..0000000000 --- a/packages/util/src/format/types.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -export interface Compact { - toBn: () => BN; - unwrap: () => BN | Date; -} diff --git a/packages/util/src/hex/addPrefix.spec.ts b/packages/util/src/hex/addPrefix.spec.ts deleted file mode 100644 index fda83d2a02..0000000000 --- a/packages/util/src/hex/addPrefix.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexAddPrefix } from '.'; - -describe('hexAddPrefix', () => { - it('does not add when prefix is available', () => { - expect( - hexAddPrefix('0x0123') - ).toEqual('0x0123'); - }); - - it('adds the prefix when it is not available', () => { - expect( - hexAddPrefix('0123') - ).toEqual('0x0123'); - }); - - it('adds extra 0 when length % 2 === 1', () => { - expect( - hexAddPrefix('123') - ).toEqual('0x0123'); - }); - - it('returns null as 0x', () => { - expect( - hexAddPrefix(null) - ).toEqual('0x'); - }); -}); diff --git a/packages/util/src/hex/addPrefix.ts b/packages/util/src/hex/addPrefix.ts deleted file mode 100644 index 43dbf78f2e..0000000000 --- a/packages/util/src/hex/addPrefix.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hasPrefix from './hasPrefix'; - -/** - * @name hexAddPrefix - * @summary Adds the `0x` prefix to string values. - * @description - * Returns a `0x` prefixed string from the input value. If the input is already prefixed, it is returned unchanged. - * @example - *
- * - * ```javascript - * import { hexAddPrefix } from '@plugnet/util'; - * - * console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12 - * ``` - */ -export default function hexAddPrefix (value?: string | null): string { - if (value && hasPrefix(value)) { - return value; - } - - const prefix = value && value.length % 2 === 1 - ? '0' - : ''; - - return `0x${prefix}${value || ''}`; -} diff --git a/packages/util/src/hex/fixLength.spec.ts b/packages/util/src/hex/fixLength.spec.ts deleted file mode 100644 index 93bc99aeb9..0000000000 --- a/packages/util/src/hex/fixLength.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexFixLength } from '.'; - -describe('hexFixLength', () => { - it('returns bitLength === -1 as-is', () => { - expect( - hexFixLength('0x12345678') - ).toEqual('0x12345678'); - }); - - it('returns bitLength === -1 as-is (adding missing 0)', () => { - expect( - hexFixLength('0x1234567') - ).toEqual('0x01234567'); - }); - - it('does not change when bitlength === length', () => { - expect( - hexFixLength('0x12345678', 32) - ).toEqual('0x12345678'); - }); - - it('trims values when bitLength > length', () => { - expect( - hexFixLength('0x12345678', 16) - ).toEqual('0x5678'); - }); - - it('returns as-is when bitLength < length', () => { - expect( - hexFixLength('0x1234', 32) - ).toEqual('0x1234'); - }); - - it('adds zeros when bitLength < length (withPadded)', () => { - expect( - hexFixLength('0x1234', 32, true) - ).toEqual('0x00001234'); - }); -}); diff --git a/packages/util/src/hex/fixLength.ts b/packages/util/src/hex/fixLength.ts deleted file mode 100644 index 54763d62a6..0000000000 --- a/packages/util/src/hex/fixLength.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hexAddPrefix from './addPrefix'; -import hexStripPrefix from './stripPrefix'; - -/** - * @name hexFixLength - * @summary Shifts a hex string to a specific bitLength - * @description - * Returns a `0x` prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`. - * @example - *
- * - * ```javascript - * import { hexFixLength } from '@plugnet/util'; - * - * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12 - * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012 - * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12 - * ``` - */ -export default function hexFixLength (value: string, bitLength: number = -1, withPadding: boolean = false): string { - const strLength = Math.ceil(bitLength / 4); - const hexLength = strLength + 2; - - if (bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength)) { - return hexAddPrefix( - hexStripPrefix(value) - ); - } - - if (value.length > hexLength) { - return hexAddPrefix( - hexStripPrefix(value).slice(-1 * strLength) - ); - } - - return hexAddPrefix( - `${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength) - ); -} diff --git a/packages/util/src/hex/hasPrefix.spec.ts b/packages/util/src/hex/hasPrefix.spec.ts deleted file mode 100644 index bb10a86a95..0000000000 --- a/packages/util/src/hex/hasPrefix.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexHasPrefix } from '.'; - -describe('hexHasPrefix', () => { - it('returns true when hex prefix is found', () => { - expect( - hexHasPrefix('0x123') - ).toEqual(true); - }); - - it('returns false when no prefix attached', () => { - expect( - hexHasPrefix('123') - ).toEqual(false); - }); - - it('returns false when null value supplied', () => { - expect( - hexHasPrefix(null) - ).toEqual(false); - }); - - it('returns false when non-string value supplied', () => { - expect( - hexHasPrefix(false as any) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/hex/hasPrefix.ts b/packages/util/src/hex/hasPrefix.ts deleted file mode 100644 index ead8f2ae6b..0000000000 --- a/packages/util/src/hex/hasPrefix.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isHex from '../is/hex'; - -/** - * @name hexHasPrefix - * @summary Tests for the existence of a `0x` prefix. - * @description - * Checks for a valid hex input value and if the start matched `0x` - * @example - *
- * - * ```javascript - * import { hexHasPrefix } from '@plugnet/util'; - * - * console.log('has prefix', hexHasPrefix('0x1234')); // => true - * ``` - */ -export default function hexHasPrefix (value?: string | null): boolean { - return !!(value && isHex(value, -1, true) && value.substr(0, 2) === '0x'); -} diff --git a/packages/util/src/hex/index.ts b/packages/util/src/hex/index.ts deleted file mode 100644 index acf2fe50fa..0000000000 --- a/packages/util/src/hex/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Internal utilities to create and test for hex values - */ - -export { default as hexAddPrefix } from './addPrefix'; -export { default as hexFixLength } from './fixLength'; -export { default as hexHasPrefix } from './hasPrefix'; -export { default as hexStripPrefix } from './stripPrefix'; -export { default as hexToBn } from './toBn'; -export { default as hexToNumber } from './toNumber'; -export { default as hexToU8a } from './toU8a'; diff --git a/packages/util/src/hex/stripPrefix.spec.ts b/packages/util/src/hex/stripPrefix.spec.ts deleted file mode 100644 index 46aca5155e..0000000000 --- a/packages/util/src/hex/stripPrefix.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexStripPrefix } from '.'; - -describe('hexStripPrefix', () => { - it('returns an empty string when null value supplied', () => { - expect( - hexStripPrefix(null) - ).toEqual(''); - }); - - it('strips the prefix from hex strings', () => { - expect( - hexStripPrefix('0x1223') - ).toEqual('1223'); - }); - - it('returns un-prefixed hex as-is', () => { - expect( - hexStripPrefix('abcd1223') - ).toEqual('abcd1223'); - }); - - it('throws when invalid hex', () => { - expect( - () => hexStripPrefix('0x0x01ab') - ).toThrow(/Invalid hex/); - }); -}); diff --git a/packages/util/src/hex/stripPrefix.ts b/packages/util/src/hex/stripPrefix.ts deleted file mode 100644 index f0dfbb1b76..0000000000 --- a/packages/util/src/hex/stripPrefix.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hasPrefix from './hasPrefix'; - -const UNPREFIX_HEX_REGEX = /^[a-fA-F0-9]+$/; - -/** - * @name hexStripPrefix - * @summary Strips any leading `0x` prefix. - * @description - * Tests for the existence of a `0x` prefix, and returns the value without the prefix. Un-prefixed values are returned as-is. - * @example - *
- * - * ```javascript - * import { hexStripPrefix } from '@plugnet/util'; - * - * console.log('stripped', hexStripPrefix('0x1234')); // => 1234 - * ``` - */ -export default function hexStripPrefix (value?: string | null): string { - if (!value) { - return ''; - } - - if (hasPrefix(value)) { - return value.substr(2); - } - - if (UNPREFIX_HEX_REGEX.test(value)) { - return value; - } - - throw new Error(`Invalid hex ${value} passed to hexStripPrefix`); -} diff --git a/packages/util/src/hex/toBn.spec.ts b/packages/util/src/hex/toBn.spec.ts deleted file mode 100644 index 41f4cead14..0000000000 --- a/packages/util/src/hex/toBn.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToBn } from '.'; - -describe('hexToBn', () => { - it('converts prefixed hex values to BN', () => { - expect( - hexToBn(0x81).toString(16) - ).toBe('81'); - }); - - it('converts null values to BN(0)', () => { - expect( - hexToBn(null).toNumber() - ).toBe(0); - }); - - it('converts 0x values to BN(0)', () => { - expect( - hexToBn('0x').toNumber() - ).toBe(0); - }); - - it('should convert with Big Endian by default', () => { - expect( - hexToBn('0x0100').toNumber() - ).toBe(256); - }); - - it('converts 0x values to BN(0) (LE)', () => { - expect( - hexToBn('0x', { isLe: true }).toNumber() - ).toBe(0); - }); - - it('converts little-endian', () => { - expect( - hexToBn('0x4500000000000000', { isLe: true }).toNumber() - ).toBe(69); - }); - - it('handles negative numbers (LE)', () => { - expect( - hexToBn('0x2efb', { isLe: true, isNegative: true }).toNumber() - ).toBe(-1234); - }); - - it('handles negative numbers (BE)', () => { - expect( - hexToBn('0xfb2e', { isLe: false, isNegative: true }).toNumber() - ).toBe(-1234); - }); - - it('handles starting zeros correctly (BE)', () => { - expect( - hexToBn('0x0000000000000100', { isLe: false }).toNumber() - ).toBe(256); - }); - - it('handles starting zeros correctly (LE)', () => { - expect( - hexToBn('0x0001000000000000', { isLe: true }).toNumber() - ).toBe(256); - }); - - it('handles backwards compatibility', () => { - expect( - hexToBn('0x0001000000000000', false).eq( - hexToBn('0x0001000000000000', { isLe: false }) - ) - ).toBe(true); - expect( - hexToBn('0x0001000000000000', true).eq( - hexToBn('0x0001000000000000', { isLe: true }) - ) - ).toBe(true); - }); -}); diff --git a/packages/util/src/hex/toBn.ts b/packages/util/src/hex/toBn.ts deleted file mode 100644 index 6a0c7c756c..0000000000 --- a/packages/util/src/hex/toBn.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import isBoolean from '../is/boolean'; -import hexStripPrefix from './stripPrefix'; -import { ToBnOptions } from '../types'; - -function reverse (value: string): string { - return (value.match(new RegExp('.{1,2}', 'g')) || []) - .reverse() - .join(''); -} - -/** - * @name hexToBn - * @summary Creates a BN.js bignumber object from a hex string. - * @description - * `null` inputs returns a `BN(0)` result. Hex input values return the actual value converted to a BN. Anything that is not a hex string (including the `0x` prefix) throws an error. - * @param _value The value to convert - * @param _options Options to pass while converting - * @param _options.isLe Convert using Little Endian - * @param _options.isNegative Convert using two's complement - * @example - *
- * - * ```javascript - * import { hexToBn } from '@plugnet/util'; - * - * hexToBn('0x123480001f'); // => BN(0x123480001f) - * ``` - */ -export default function hexToBn ( - value?: string | number | null, - options: ToBnOptions | boolean = { isLe: false, isNegative: false } -): BN { - if (!value) { - return new BN(0); - } - - const _options: ToBnOptions = { - isLe: false, - isNegative: false, - // Backwards-compatibility - ...(isBoolean(options) ? { isLe: options } : options) - }; - - const _value = hexStripPrefix(value as string); - - // FIXME: Use BN's 3rd argument `isLe` once this issue is fixed - // https://github.com/indutny/bn.js/issues/208 - const bn = new BN((_options.isLe ? reverse(_value) : _value) || '00', 16); - - // fromTwos takes as parameter the number of bits, which is the hex length - // multiplied by 4. - return _options.isNegative ? bn.fromTwos(_value.length * 4) : bn; -} diff --git a/packages/util/src/hex/toNumber.spec.ts b/packages/util/src/hex/toNumber.spec.ts deleted file mode 100644 index 5e67dfbd14..0000000000 --- a/packages/util/src/hex/toNumber.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToNumber } from '.'; - -describe('hexToNumber', () => { - it('converts an empty to NaN', () => { - expect( - hexToNumber() - ).toEqual(NaN); - }); - - it('converts to a number from hex', () => { - expect( - hexToNumber('0x1234') - ).toEqual(0x1234); - }); -}); diff --git a/packages/util/src/hex/toNumber.ts b/packages/util/src/hex/toNumber.ts deleted file mode 100644 index 047de0e9f7..0000000000 --- a/packages/util/src/hex/toNumber.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hexToBn from './toBn'; - -/** - * @name hexToNumber - * @summary Creates a Number value from a Buffer object. - * @description - * `null` inputs returns an NaN result, `hex` values return the actual value as a `Number`. - * @example - *
- * - * ```javascript - * import { hexToNumber } from '@plugnet/util'; - * - * hexToNumber('0x1234'); // => 0x1234 - * ``` - */ -export default function hexToNumber (value?: string | null): number { - if (!value) { - return NaN; - } - - return hexToBn(value).toNumber(); -} diff --git a/packages/util/src/hex/toU8a.spec.ts b/packages/util/src/hex/toU8a.spec.ts deleted file mode 100644 index f43b88af78..0000000000 --- a/packages/util/src/hex/toU8a.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { hexToU8a } from '.'; - -describe('hexToU8a', () => { - it('returns an empty Uint8Array when null provided', () => { - expect( - hexToU8a(null) - ).toHaveLength(0); - }); - - it('returns a Uint8Array with the correct values', () => { - expect( - hexToU8a('0x80000a') - ).toEqual( - new Uint8Array([128, 0, 10]) - ); - }); - - it('returns a Uint8Array with the correct values (bitLengfth)', () => { - expect( - hexToU8a('0x80000a', 32) - ).toEqual( - new Uint8Array([0, 128, 0, 10]) - ); - }); - - it('fails when non-hex value provided', () => { - expect( - () => hexToU8a('notahex') - ).toThrow(/hex value to convert/); - }); -}); diff --git a/packages/util/src/hex/toU8a.ts b/packages/util/src/hex/toU8a.ts deleted file mode 100644 index dcedb0ea10..0000000000 --- a/packages/util/src/hex/toU8a.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import assert from '../assert'; -import isHex from '../is/hex'; -import hexStripPrefix from './stripPrefix'; - -/** - * @name hexToU8a - * @summary Creates a Buffer object from a hex string. - * @description - * `null` inputs returns an empty `Uint8Array` result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the `0x` prefix) throws an error. - * @example - *
- * - * ```javascript - * import { hexToU8a } from '@plugnet/util'; - * - * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f]) - * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f]) - * ``` - */ -export default function hexToU8a (_value?: string | null, bitLength: number = -1): Uint8Array { - if (!_value) { - return new Uint8Array([]); - } - - assert(isHex(_value), `Expected hex value to convert, found '${_value}'`); - - const value = hexStripPrefix(_value); - const valLength = value.length / 2; - const bufLength = Math.ceil( - bitLength === -1 - ? valLength - : bitLength / 8 - ); - const result = new Uint8Array(bufLength); - const offset = Math.max(0, bufLength - valLength); - - for (let index = 0; index < bufLength; index++) { - result[index + offset] = parseInt(value.substr(index * 2, 2), 16); - } - - return result; -} diff --git a/packages/util/src/index.spec.ts b/packages/util/src/index.spec.ts deleted file mode 100644 index 2ae6940ead..0000000000 --- a/packages/util/src/index.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { assert } from '.'; - -describe('index', () => { - it('exports ok', () => { - expect(assert).toBeDefined(); - }); -}); diff --git a/packages/util/src/index.ts b/packages/util/src/index.ts deleted file mode 100644 index 3bb8f1112c..0000000000 --- a/packages/util/src/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import './polyfill'; - -/** - * @summary Utility methods for this package are split into groups - */ - -export { default as assert } from './assert'; -export { default as assertSingletonPackage } from './assertSingletonPackage'; -export { default as logger } from './logger'; -export { default as promisify } from './promisify'; - -export * from './array'; -export * from './bn'; -export * from './buffer'; -export * from './compact'; -export * from './ext'; -export * from './format'; -export * from './hex'; -export * from './is'; -export * from './number'; -export * from './string'; -export * from './u8a'; diff --git a/packages/util/src/is/bn.spec.ts b/packages/util/src/is/bn.spec.ts deleted file mode 100644 index 3bfc85ea24..0000000000 --- a/packages/util/src/is/bn.spec.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import { isBn } from '.'; - -describe('isBN', () => { - it('returns true when a BN value', () => { - expect( - isBn(new BN(123)) - ).toEqual(true); - }); - - it('returns false on non-BN values', () => { - expect( - isBn(0) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/bn.ts b/packages/util/src/is/bn.ts deleted file mode 100644 index 4bbb95828f..0000000000 --- a/packages/util/src/is/bn.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -/** - * @name isBn - * @summary Tests for a `BN` object instance. - * @description - * Checks to see if the input object is an instance of `BN` (bn.js). - * @example - *
- * - * ```javascript - * import BN from 'bn.js'; - * import { isBn } from '@plugnet/util'; - * - * console.log('isBn', isBn(new BN(1))); // => true - * ``` - */ -export default function isBn (value: any): value is BN { - return BN.isBN(value); -} diff --git a/packages/util/src/is/boolean.spec.ts b/packages/util/src/is/boolean.spec.ts deleted file mode 100644 index 914d8ff7d4..0000000000 --- a/packages/util/src/is/boolean.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isBoolean } from '.'; - -describe('isBoolean', () => { - it('returns true on false', () => { - expect( - isBoolean(false) - ).toEqual(true); - }); - - it('returns true on true', () => { - expect( - isBoolean(true) - ).toEqual(true); - }); - - it('returns false on invalid booleans', () => { - expect( - isBoolean('notABool') - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/boolean.ts b/packages/util/src/is/boolean.ts deleted file mode 100644 index 9e7da849e3..0000000000 --- a/packages/util/src/is/boolean.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isBoolean - * @summary Tests for a boolean value. - * @description - * Checks to see if the input value is a JavaScript boolean. - * @example - *
- * - * ```javascript - * import { isBoolean } from '@plugnet/util'; - * - * isBoolean(false); // => true - * ``` - */ -export default function isBoolean (value: any): value is boolean { - return typeof value === 'boolean'; -} diff --git a/packages/util/src/is/buffer.spec.ts b/packages/util/src/is/buffer.spec.ts deleted file mode 100644 index 6704044811..0000000000 --- a/packages/util/src/is/buffer.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isBuffer } from '.'; - -describe('isBuffer', () => { - it('returns true when a Buffer value', () => { - expect( - isBuffer(Buffer.from([])) - ).toEqual(true); - }); - - it('returns false on non-Buffer values', () => { - expect( - isBuffer(0) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/buffer.ts b/packages/util/src/is/buffer.ts deleted file mode 100644 index 929340ad68..0000000000 --- a/packages/util/src/is/buffer.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isInstanceOf from './instanceOf'; - -/** - * @name isBuffer - * @summary Tests for a `Buffer` object instance. - * @description - * Checks to see if the input object is an instance of `Buffer`. - * @example - *
- * - * ```javascript - * import { isBuffer } from '@plugnet/util'; - * - * console.log('isBuffer', isBuffer(Buffer.from([]))); // => true - * ``` - */ -export default function isBuffer (value: any): value is Buffer { - return isInstanceOf(value, Buffer); -} diff --git a/packages/util/src/is/error.spec.ts b/packages/util/src/is/error.spec.ts deleted file mode 100644 index f34c337b92..0000000000 --- a/packages/util/src/is/error.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isError } from '.'; - -describe('isError', () => { - it('returns true when an Error value', () => { - expect( - isError(new Error('testing')) - ).toEqual(true); - }); - - it('returns false on non-Error values', () => { - expect( - isError(0) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/error.ts b/packages/util/src/is/error.ts deleted file mode 100644 index 29063ce484..0000000000 --- a/packages/util/src/is/error.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isInstanceOf from './instanceOf'; - -/** - * @name isError - * @summary Tests for a `Error` object instance. - * @description - * Checks to see if the input object is an instance of `Error`. - * @example - *
- * - * ```javascript - * import { isError } from '@plugnet/util'; - * - * console.log('isError', isError(new Error('message'))); // => true - * ``` - */ -export default function isError (value: any): value is Error { - return isInstanceOf(value, Error); -} diff --git a/packages/util/src/is/function.spec.ts b/packages/util/src/is/function.spec.ts deleted file mode 100644 index 9b06bca20a..0000000000 --- a/packages/util/src/is/function.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isFunction } from '.'; - -describe('isFunction', () => { - it('returns true on valid functions', () => { - expect( - isFunction(isFunction) - ).toEqual(true); - }); - - it('returns false on invalid functions', () => { - expect( - isFunction('notAFunction') - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/function.ts b/packages/util/src/is/function.ts deleted file mode 100644 index 62b55a2749..0000000000 --- a/packages/util/src/is/function.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isFunction - * @summary Tests for a `function`. - * @description - * Checks to see if the input value is a JavaScript function. - * @example - *
- * - * ```javascript - * import { isFunction } from '@plugnet/util'; - * - * isFunction(() => false); // => true - * ``` - */ -export default function isFunction (value: any): value is Function { - return typeof value === 'function'; -} diff --git a/packages/util/src/is/hex.spec.ts b/packages/util/src/is/hex.spec.ts deleted file mode 100644 index 342016a36e..0000000000 --- a/packages/util/src/is/hex.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isHex } from '.'; - -describe('isHex', () => { - const test = '1234abcd'; - - it('returns true on 0x hex values', () => { - expect( - isHex('0x') - ).toEqual(true); - }); - - it('returns true on hex values', () => { - expect( - isHex(`0x${test}`) - ).toEqual(true); - }); - - it('returns true on hex values with String', () => { - expect( - isHex(new String(`0x${test}`)) - ).toEqual(true); - }); - - it('returns false on hex values (non % 2)', () => { - expect( - isHex(`0x${test}0`) - ).toEqual(false); - }); - - it('returns true on uppercase values', () => { - expect( - isHex(`0x${test.toUpperCase()}`) - ).toEqual(true); - }); - - it('return false on hex values unprefixed', () => { - expect( - isHex(test) - ).toEqual(false); - }); - - it('returns false on non-string values', () => { - expect( - isHex(false) - ).toEqual(false); - }); - - it('returns true when valid hex and bitLength matches', () => { - expect( - isHex('0x1234', 16) - ).toEqual(true); - }); - - it('returns true when valid hex and bitLength does not match', () => { - expect( - isHex('0x1234', 8) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/hex.ts b/packages/util/src/is/hex.ts deleted file mode 100644 index 62daa9c41e..0000000000 --- a/packages/util/src/is/hex.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isString from './string'; - -const HEX_REGEX = /^0x[a-fA-F0-9]+$/; - -/** - * @name isHex - * @summary Tests for a hex string. - * @description - * Checks to see if the input value is a `0x` prefixed hex string. Optionally (`bitLength` !== -1) checks to see if the bitLength is correct. - * @example - *
- * - * ```javascript - * import { isHex } from '@plugnet/util'; - * - * isHex('0x1234'); // => true - * isHex('0x1234', 8); // => false - * ``` - */ -export default function isHex (value: any, bitLength: number = -1, ignoreLength: boolean = false): value is string | String { - const isValidHex = value === '0x' || (isString(value) && HEX_REGEX.test(value.toString())); - - if (isValidHex && bitLength !== -1) { - return value.length === (2 + Math.ceil(bitLength / 4)); - } - - return isValidHex && (ignoreLength || (value.length % 2 === 0)); -} diff --git a/packages/util/src/is/index.ts b/packages/util/src/is/index.ts deleted file mode 100644 index d1cde591da..0000000000 --- a/packages/util/src/is/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Type checking utilities - */ - -export { default as isBn } from './bn'; -export { default as isBuffer } from './buffer'; -export { default as isBoolean } from './boolean'; -export { default as isError } from './error'; -export { default as isFunction } from './function'; -export { default as isHex } from './hex'; -export { default as isInstanceOf } from './instanceOf'; -export { default as isIp } from './ip'; -export { default as isJsonObject } from './jsonObject'; -export { default as isNull } from './null'; -export { default as isNumber } from './number'; -export { default as isObject } from './object'; -export { default as isObservable } from './observable'; -export { default as isString } from './string'; -export { default as isTestChain } from './testChain'; -export { default as isU8a } from './u8a'; -export { default as isUndefined } from './undefined'; diff --git a/packages/util/src/is/instanceOf.spec.ts b/packages/util/src/is/instanceOf.spec.ts deleted file mode 100644 index c83384044e..0000000000 --- a/packages/util/src/is/instanceOf.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isInstanceOf } from '.'; - -describe('isInstanceOf', () => { - it('returns true on real instances', () => { - expect( - isInstanceOf(new Array(2), Array) - ).toEqual(true); - }); - - it('returns false on non-allocated instances', () => { - expect( - isInstanceOf([], Array) - ).toEqual(true); - }); - - it('returns false on non-instances', () => { - expect( - isInstanceOf('array', Array) - ).toEqual(false); - }); - - it('returns false when class not specified', () => { - expect( - isInstanceOf('array', Array) - ).toEqual(false); - }); - - it('returns false on wrong class type', () => { - expect( - isInstanceOf(new Array(2), String) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/instanceOf.ts b/packages/util/src/is/instanceOf.ts deleted file mode 100644 index ffb06b20e7..0000000000 --- a/packages/util/src/is/instanceOf.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isInstanceOf - * @summary Tests for a instance of a class. - * @description - * Checks to see if the input value is an instance of the test class. - * @example - *
- * - * ```javascript - * import { isInstanceOf } from '@plugnet/util'; - * - * console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true - * ``` - */ -export default function isInstanceOf (value: any, clazz: any): boolean { - return value instanceof clazz; -} diff --git a/packages/util/src/is/ip.spec.ts b/packages/util/src/is/ip.spec.ts deleted file mode 100644 index 1a9210c1d6..0000000000 --- a/packages/util/src/is/ip.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isIp } from '.'; - -describe('isIp', () => { - it('returns false when non-ip found', () => { - expect( - isIp('not.an.ip.1') - ).toEqual(false); - }); - - it('returns true on IPv4 addresses', () => { - expect( - isIp('192.168.0.1') - ).toEqual(true); - }); - - it('returns true on IPv4 addresses (IPV4 type)', () => { - expect( - isIp('192.168.0.1', 'v4') - ).toEqual(true); - }); - - it('returns false on IPv4 addresses (IPv6 type)', () => { - expect( - isIp('192.168.0.1', 'v6') - ).toEqual(false); - }); - - it('returns true on IPv6 addresses', () => { - expect( - isIp('1:2:3:4:5:6:7:8') - ).toEqual(true); - }); - - it('returns true on IPv6 addresses (IPv6 type)', () => { - expect( - isIp('1:2:3:4:5:6:7:8', 'v6') - ).toEqual(true); - }); - - it('returns false on IPv6 addresses (IPv4 type)', () => { - expect( - isIp('1:2:3:4:5:6:7:8', 'v4') - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/ip.ts b/packages/util/src/is/ip.ts deleted file mode 100644 index e00ca423db..0000000000 --- a/packages/util/src/is/ip.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import ipRegex from 'ip-regex'; - -type IpTypes = 'v4' | 'v6'; - -/** - * @name isIp - * @summary Tests if the value is a valid IP address - * @description - * Checks to see if the value is a valid IP address. Optionally check for either v4/v6 - * @example - *
- * - * ```javascript - * import { isIp } from '@plugnet/util'; - * - * isIp('192.168.0.1')); // => true - * isIp('1:2:3:4:5:6:7:8'); // => true - * isIp('192.168.0.1', 'v6')); // => false - * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false - * ``` - */ -export default function isIp (value: string, type?: IpTypes): boolean { - // FIXME @types/ip-regex defintions are outdated - if (type === 'v4') { - // @ts-ignore - return ipRegex.v4({ exact: true }).test(value); - } else if (type === 'v6') { - // @ts-ignore - return ipRegex.v6({ exact: true }).test(value); - } - - return ipRegex({ exact: true }).test(value); -} diff --git a/packages/util/src/is/jsonObject.spec.ts b/packages/util/src/is/jsonObject.spec.ts deleted file mode 100644 index 002a9457d0..0000000000 --- a/packages/util/src/is/jsonObject.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isJsonObject } from '.'; - -const jsonObject = `{ - "Test": "1234", - "NestedTest": { - "Test": "5678" - } - }`; - -describe('isJsonObject', () => { - it('returns true on empty objects', () => { - expect( - isJsonObject({}) - ).toEqual(true); - }); - - it('returns true on JSON objects', () => { - expect( - isJsonObject(jsonObject) - ).toEqual(true); - }); - - it('returns false on JSON parsable value typeof number', () => { - expect( - isJsonObject(1234) - ).toEqual(false); - }); - - it('returns false on JSON parsable value null', () => { - expect( - isJsonObject(null) - ).toEqual(false); - }); - - it('returns false on invalid objects', () => { - expect( - isJsonObject('notAnObject') - ).toEqual(false); - }); - - it('returns false on invalid JSON', () => { - expect( - isJsonObject(`{"abc", "def"}`) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/jsonObject.ts b/packages/util/src/is/jsonObject.ts deleted file mode 100644 index 7eef964a91..0000000000 --- a/packages/util/src/is/jsonObject.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -type ObjectIndexed = { - [index: string]: any -}; - -/** - * @name isJsonObject - * @summary Tests for a valid JSON `object`. - * @description - * Checks to see if the input value is a valid JSON object. - * It returns false if the input is JSON parsable, but not an Javascript object. - * @example - *
- * - * ```javascript - * import { isJsonObject } from '@plugnet/util'; - * - * isJsonObject({}); // => true - * isJsonObject({ - * "Test": "1234", - * "NestedTest": { - * "Test": "5678" - * } - * }); // => true - * isJsonObject(1234); // JSON parsable, but not an object => false - * isJsonObject(null); // JSON parsable, but not an object => false - * isJsonObject('not an object'); // => false - * ``` - */ - -export default function isJsonObject (value: any): value is ObjectIndexed { - - value = typeof value !== 'string' - ? JSON.stringify(value) - : value; - - try { - value = JSON.parse(value); - - return (typeof value === 'object' && value !== null); - } catch (e) { - return false; - } -} diff --git a/packages/util/src/is/null.spec.ts b/packages/util/src/is/null.spec.ts deleted file mode 100644 index 96bde2dba4..0000000000 --- a/packages/util/src/is/null.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isNull } from '.'; - -describe('isNull', () => { - it('returns true when a null value', () => { - expect( - isNull(null) - ).toEqual(true); - }); - - it('returns false on non-null values', () => { - expect( - isNull() - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/null.ts b/packages/util/src/is/null.ts deleted file mode 100644 index 5a34fefef8..0000000000 --- a/packages/util/src/is/null.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isNull - * @summary Tests for a `null` values. - * @description - * Checks to see if the input value is `null`. - * @example - *
- * - * ```javascript - * import { isNull } from '@plugnet/util'; - * - * console.log('isNull', isNull(null)); // => true - * ``` - */ -export default function isNull (value?: any): value is null { - return value === null; -} diff --git a/packages/util/src/is/number.spec.ts b/packages/util/src/is/number.spec.ts deleted file mode 100644 index 2617550db5..0000000000 --- a/packages/util/src/is/number.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isNumber } from '.'; - -describe('isNumber', () => { - it('returns true on valid numbers', () => { - expect( - isNumber(2) - ).toEqual(true); - }); - - it('returns false on invalid numbers', () => { - expect( - isNumber('2') - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/number.ts b/packages/util/src/is/number.ts deleted file mode 100644 index a5c7a0bd5a..0000000000 --- a/packages/util/src/is/number.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isNumber - * @summary Tests for a JavaScript number. - * @description - * Checks to see if the input value is a valid number. - * @example - *
- * - * ```javascript - * import { isNumber } from '@plugnet/util'; - * - * console.log('isNumber', isNumber(1234)); // => true - * ``` - */ -export default function isNumber (value: any): value is number { - return typeof value === 'number'; -} diff --git a/packages/util/src/is/object.spec.ts b/packages/util/src/is/object.spec.ts deleted file mode 100644 index d0ea408f54..0000000000 --- a/packages/util/src/is/object.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isObject } from '.'; - -describe('isObject', () => { - it('returns true on valid objects', () => { - expect( - isObject({}) - ).toEqual(true); - }); - - it('returns false on invalid objects', () => { - expect( - isObject('notAnObject') - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/object.ts b/packages/util/src/is/object.ts deleted file mode 100644 index d9ed8d3e57..0000000000 --- a/packages/util/src/is/object.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -type ObjectIndexed = { - [index: string]: any -}; - -/** - * @name isObject - * @summary Tests for an `object`. - * @description - * Checks to see if the input value is a JavaScript object. - * @example - *
- * - * ```javascript - * import { isObject } from '@plugnet/util'; - * - * isObject({}); // => true - * isObject('something'); // => false - * ``` - */ -export default function isObject (value: any): value is ObjectIndexed { - return typeof value === 'object'; -} diff --git a/packages/util/src/is/observable.spec.ts b/packages/util/src/is/observable.spec.ts deleted file mode 100644 index e697272dc5..0000000000 --- a/packages/util/src/is/observable.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isObservable } from '.'; - -describe('isObservable', () => { - it('returns true on valid observables', () => { - expect( - isObservable({ next: () => true }) - ).toEqual(true); - }); - - it('returns false on invalid objects', () => { - expect( - isObservable('notAnObservable') - ).toEqual(false); - }); - - it('returns false on invalid next functions', () => { - expect( - isObservable({ next: true }) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/observable.ts b/packages/util/src/is/observable.ts deleted file mode 100644 index fe8d29b738..0000000000 --- a/packages/util/src/is/observable.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isFunction from './function'; -import isObject from './object'; - -type Observable = { - next: (...paarams: any[]) => any -}; - -/** - * @name isBObservable - * @summary Tests for a `Observable` object instance. - * @description - * Checks to see if the input object is an instance of `BN` (bn.js). - * @example - *
- * - * ```javascript - * import { isObservable } from '@plugnet/util'; - * - * console.log('isObservable', isObservable(...)); - * ``` - */ -export default function isObservable (value: any): value is Observable { - return isObject(value) && isFunction((value as Observable).next); -} diff --git a/packages/util/src/is/string.spec.ts b/packages/util/src/is/string.spec.ts deleted file mode 100644 index 0f2e17fee3..0000000000 --- a/packages/util/src/is/string.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isString } from '.'; - -describe('isString', () => { - it('returns true on valid strings', () => { - expect( - isString('123') - ).toEqual(true); - }); - - it('returns true on empty strings', () => { - expect( - isString('') - ).toEqual(true); - }); - - it('returns true on String object', () => { - expect( - isString(new String('foo')) - ).toEqual(true); - }); - - it('returns false on invalid numbers', () => { - expect( - isString(2) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/string.ts b/packages/util/src/is/string.ts deleted file mode 100644 index 25bba62f56..0000000000 --- a/packages/util/src/is/string.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isString - * @summary Tests for a string. - * @description - * Checks to see if the input value is a JavaScript string. - * @example - *
- * - * ```javascript - * import { isString } from '@plugnet/util'; - * - * console.log('isString', isString('test')); // => true - * ``` - */ -export default function isString (value: any): value is string | String { - return typeof value === 'string' || value instanceof String; -} diff --git a/packages/util/src/is/testChain.spec.ts b/packages/util/src/is/testChain.spec.ts deleted file mode 100644 index 7fb8e1f3c1..0000000000 --- a/packages/util/src/is/testChain.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isTestChain from './testChain'; - -describe('isTestChain', () => { - it('enables test environment when chain specification matches text of dev or loc(al)', () => { - const validTestModeChainSpecsWithDev = ['Development']; - const validTestModeChainSpecsWithLoc = ['Local Testnet']; - - validTestModeChainSpecsWithDev.concat(validTestModeChainSpecsWithLoc).forEach((s) => - expect(isTestChain(s)).toEqual(true) - ); - }); - - it('disables keyring test mode when chain specification is not a test mode or undefined or number type', () => { - const invalidTestModeChainSpecs = ['dev', 'local', 'development', 'PoC-1 Testnet', 'Staging Testnet', 'future PoC-2 Testnet', 'a pocadot?', undefined]; - - invalidTestModeChainSpecs.forEach((s) => - expect(isTestChain(s)).toEqual(false) - ); - }); -}); diff --git a/packages/util/src/is/testChain.ts b/packages/util/src/is/testChain.ts deleted file mode 100644 index 4238327a6e..0000000000 --- a/packages/util/src/is/testChain.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -const re = new RegExp('^(Development|Local Testnet)$'); - -export default function isTestChain (chain?: string | null): boolean { - if (!chain) { - return false; - } - - return !!re.test(chain.toString()); -} diff --git a/packages/util/src/is/u8a.spec.ts b/packages/util/src/is/u8a.spec.ts deleted file mode 100644 index f1196b61c9..0000000000 --- a/packages/util/src/is/u8a.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isU8a } from '.'; - -describe('isUint8Array', () => { - it('returns false on undefined values', () => { - expect( - isU8a() - ).toEqual(false); - }); - - it('returns false on Array values', () => { - expect( - isU8a([]) - ).toEqual(false); - }); - - it('returns true on Uint8Array values', () => { - expect( - isU8a(new Uint8Array([])) - ).toEqual(true); - }); -}); diff --git a/packages/util/src/is/u8a.ts b/packages/util/src/is/u8a.ts deleted file mode 100644 index 3b1bbfcf4f..0000000000 --- a/packages/util/src/is/u8a.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isInstanceOf from './instanceOf'; - -/** - * @name isU8a - * @summary Tests for a `Uint8Array` object instance. - * @description - * Checks to see if the input object is an instance of `Uint8Array`. - * @example - *
- * - * ```javascript - * import { isUint8Array } from '@plugnet/util'; - * - * console.log('isU8a', isU8a([])); // => false - * ``` - */ -export default function isU8a (value?: any): value is Uint8Array { - return isInstanceOf(value, Uint8Array); -} diff --git a/packages/util/src/is/undefined.spec.ts b/packages/util/src/is/undefined.spec.ts deleted file mode 100644 index 84a1226c7e..0000000000 --- a/packages/util/src/is/undefined.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { isUndefined } from '.'; - -describe('isUndefined', () => { - it('returns true on undefined values', () => { - expect( - isUndefined() - ).toEqual(true); - }); - - it('returns false on defined values', () => { - expect( - isUndefined(null) - ).toEqual(false); - }); -}); diff --git a/packages/util/src/is/undefined.ts b/packages/util/src/is/undefined.ts deleted file mode 100644 index 34bb725167..0000000000 --- a/packages/util/src/is/undefined.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name isUndefined - * @summary Tests for a `undefined` values. - * @description - * Checks to see if the input value is `undefined`. - * @example - *
- * - * ```javascript - * import { isUndefined } from '@plugnet/util'; - * - * console.log('isUndefined', isUndefined(void(0))); // => true - * ``` - */ -export default function isUndefined (value?: any): value is undefined { - return typeof value === 'undefined'; -} diff --git a/packages/util/src/logger.spec.ts b/packages/util/src/logger.spec.ts deleted file mode 100644 index dafb2eb864..0000000000 --- a/packages/util/src/logger.spec.ts +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { logger } from '.'; -import { format } from './logger'; - -describe('logger', () => { - let dateMatch: any; - let prefixMatch: any; - let l: any; - let ln: any; - let spy: any; - let oldEnv: any; - - beforeEach(() => { - oldEnv = process.env; - process.env.NODE_ENV = 'development'; - - ln = logger('notDebug'); - - process.env.DEBUG = 'test'; - - l = logger('test'); - - spy = { - error: jest.fn(), - log: jest.fn(), - warn: jest.fn() - }; - (global as any).console = spy; - - dateMatch = expect.stringMatching(/20[0-9]{2}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/); - prefixMatch = expect.stringMatching(/TEST:/); - }); - - afterEach(() => { - process.env = oldEnv; - jest.restoreAllMocks(); - }); - - describe('format', () => { - it('returns null as-is', () => { - expect(format(null)).toEqual(null); - }); - - it('returns undefined as-is', () => { - expect(format(undefined)).toEqual(undefined); - }); - }); - - it('logs to console.log with .log', () => { - l.log('console.log test'); - - expect(spy.log).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('console.log test') - ); - }); - - it('logs with mulptiple values', () => { - l.log('test', 'a', 2); - - expect(spy.log).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('test'), - expect.stringMatching('a'), - 2 - ); - }); - - it('logs when called with function', () => { - l.log(() => 'a function test'); - - expect(spy.log).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('a function test') - ); - }); - - it('logs to console.error with .error', () => { - l.error('console.error test'); - - expect(spy.error).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('console.error test') - ); - }); - - it('logs to console.warn with .warn', () => { - l.warn('console.warn test'); - - expect(spy.warn).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('console.warn test') - ); - }); - - it('does debug log when DEBUG specified', () => { - l.debug('test'); - - expect(spy.log).toHaveBeenCalledWith( - dateMatch, - prefixMatch, - expect.stringMatching('test') - ); - }); - - it('does debug log when DEBUG partial specified', () => { - l = logger('testing'); - l.debug('test'); - - expect(spy.log).toHaveBeenCalledWith( - dateMatch, - expect.stringMatching(/TESTING:/), - expect.stringMatching('test') - ); - }); - - it('does not debug log when non-matching DEBUG specified', () => { - process.env.DEBUG = 'blah'; - - l = logger('test'); - l.debug('test'); - - expect(spy.log).not.toHaveBeenCalled(); - }); - - it('does debug log when NODE_ENV=test specified', () => { - process.env.DEBUG = 'blah'; - process.env.NODE_ENV = 'test'; - - l = logger('test'); - l.debug('test'); - - expect(spy.log).toHaveBeenCalled(); - }); - - it('does not debug log when no process.env', () => { - process.env = void 0 as any; - - l = logger('test'); - l.debug('test'); - - expect(spy.log).not.toHaveBeenCalled(); - }); - - it('does not debug log when no DEBUG specified', () => { - ln.debug('test'); - - expect(spy.log).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/util/src/logger.ts b/packages/util/src/logger.ts deleted file mode 100644 index 2613dace12..0000000000 --- a/packages/util/src/logger.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { Logger, Logger$Data } from './types'; - -import chalk from 'chalk'; -import moment from 'moment'; - -import isBn from './is/bn'; -import isBuffer from './is/buffer'; -import isFunction from './is/function'; -import isObject from './is/object'; -import isU8a from './is/u8a'; -import u8aToHex from './u8a/toHex'; - -type ConsoleType = 'error' | 'log' | 'warn'; -type LogType = ConsoleType | 'debug'; - -const logTo = { - debug: 'log', - error: 'error', - log: 'log', - warn: 'warn' -}; - -const chalked = { - debug: chalk.gray, - error: chalk.red, - log: chalk.reset, - warn: chalk.yellow -}; - -function formatObject (value: { [index: string]: any }): any { - return Object.keys(value).reduce((result, key) => { - result[key] = format(value[key]); - - return result; - }, {} as { [index: string]: any }); -} - -export function format (value: any): any { - if (Array.isArray(value)) { - return value.map(format); - } - - if (isBn(value)) { - return value.toString(); - } - - if (isBuffer(value)) { - return `0x${value.toString('hex')}`; - } - - if (isU8a(value)) { - return u8aToHex(value); - } - - if (value && isObject(value) && value.constructor === Object) { - return formatObject(value); - } - - return value; -} - -function apply (log: LogType, type: string, values: Logger$Data): void { - if (values.length === 1 && isFunction(values[0])) { - const fnResult = (values[0] as Function)(); - - return apply(log, type, Array.isArray(fnResult) ? fnResult : [fnResult]); - } - - const chalk = (value: string): string => - chalked[log](value); - - // @ts-ignore Not sure how to coax TS here... - console[logTo[log]].apply( - console, [ - chalk(moment().format('YYYY-MM-DD HH:mm:ss')), chalk(type) - ].concat( - values.map(format) - ) - ); -} - -function noop (...values: Logger$Data): void { - // noop -} - -/** - * @name Logger - * @summary Creates a consistent log interface for messages - * @description - * Returns a `Logger` that has `.log`, `.error`, `.warn` and `.debug` (controlled with environment `DEBUG=typeA,typeB`) methods. Logging is done with a consistent prefix (type of logger, date) followed by the actual message using the underlying console. - * @example - *
- * - * ```javascript - * const l from '@plugnet/util/logger')('test'); - * - * l.log('blah'); // TEST: blah - * ``` - */ -export default function logger (_type: string): Logger { - const type = `${_type.toUpperCase()}:`.padStart(16); - let isDebug; - - try { - const isTest = process.env.NODE_ENV === 'test'; - const debugList = (process.env.DEBUG || '').split(','); - - isDebug = isTest || !!debugList.find((entry) => _type.indexOf(entry) === 0); - } catch (error) { - isDebug = false; - } - - return { - debug: isDebug - ? (...values: Logger$Data): void => apply('debug', type, values) - : noop, - error: (...values: Logger$Data): void => apply('error', type, values), - log: (...values: Logger$Data): void => apply('log', type, values), - noop, - warn: (...values: Logger$Data): void => apply('warn', type, values) - }; -} diff --git a/packages/util/src/number/index.ts b/packages/util/src/number/index.ts deleted file mode 100644 index 8a6fb9b252..0000000000 --- a/packages/util/src/number/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods to convert to and from `number` values - */ - -export { default as numberToHex } from './toHex'; -export { default as numberToU8a } from './toU8a'; diff --git a/packages/util/src/number/toHex.spec.ts b/packages/util/src/number/toHex.spec.ts deleted file mode 100644 index 016db91260..0000000000 --- a/packages/util/src/number/toHex.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { numberToHex } from '.'; - -describe('numberToHex', () => { - it('converts undefined to 0x', () => { - expect( - numberToHex() - ).toEqual('0x'); - }); - - it('converts null to 0x', () => { - expect( - numberToHex(null) - ).toEqual('0x'); - }); - - it('converts Nan to 0x', () => { - expect( - numberToHex(NaN) - ).toEqual('0x'); - }); - - it('converts 0 to 0x00', () => { - expect( - numberToHex(0) - ).toEqual('0x00'); - }); - - it('converts number to hex', () => { - expect( - numberToHex(0x1245) - ).toEqual('0x1245'); - }); - - it('converts number to hex (specfified bitLength)', () => { - expect( - numberToHex(0x1245, 32) - ).toEqual('0x00001245'); - }); -}); diff --git a/packages/util/src/number/toHex.ts b/packages/util/src/number/toHex.ts deleted file mode 100644 index 7aa97b22ab..0000000000 --- a/packages/util/src/number/toHex.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hexFixLength from '../hex/fixLength'; -import isNull from '../is/null'; -import isUndefined from '../is/undefined'; - -/** - * @name numberToHex - * @summary Creates a hex value from a number. - * @description - * `null`/`undefined`/`NaN` inputs returns an empty `0x` result. `number` input values return the actual bytes value converted to a `hex`. With `bitLength` set, it converts the number to the equivalent size. - * @example - *
- * - * ```javascript - * import { numberToHex } from '@plugnet/util'; - * - * numberToHex(0x1234); // => '0x1234' - * numberToHex(0x1234, 32); // => 0x00001234 - * ``` - */ -export default function numberToHex (value?: number | null, bitLength: number = -1): string { - if (isUndefined(value) || isNull(value) || isNaN(value)) { - return '0x'; - } - - return hexFixLength( - (value || 0).toString(16), - bitLength, - true - ); -} diff --git a/packages/util/src/number/toU8a.spec.ts b/packages/util/src/number/toU8a.spec.ts deleted file mode 100644 index 310d941ac5..0000000000 --- a/packages/util/src/number/toU8a.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { numberToU8a } from '.'; - -describe('numberToU8a', () => { - it('converts 0 to empty', () => { - expect( - numberToU8a(0) - ).toEqual(new Uint8Array([])); - }); - - it('converts undefined to empty', () => { - expect( - numberToU8a() - ).toEqual(new Uint8Array([])); - }); - - it('converts null to empty', () => { - expect( - numberToU8a(null) - ).toEqual(new Uint8Array([])); - }); - - it('converts NaN to empty', () => { - expect( - numberToU8a(NaN) - ).toEqual(new Uint8Array([])); - }); - - it('converts values to the u8a', () => { - expect( - numberToU8a(0x3456) - ).toEqual(new Uint8Array([0x34, 0x56])); - }); - - it('converts values to the u8a (bitLength)', () => { - expect( - numberToU8a(0x3456, 32) - ).toEqual(new Uint8Array([0x00, 0x00, 0x34, 0x56])); - }); -}); diff --git a/packages/util/src/number/toU8a.ts b/packages/util/src/number/toU8a.ts deleted file mode 100644 index 3755fb1665..0000000000 --- a/packages/util/src/number/toU8a.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import hexToU8a from '../hex/toU8a'; -import numberToHex from './toHex'; - -/** - * @name numberToU8a - * @summary Creates a Uint8Array object from a number. - * @description - * `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `number` input values return the actual bytes value converted to a `Uint8Array`. With `bitLength`, it converts the value to the equivalent size. - * @example - *
- * - * ```javascript - * import { numberToU8a } from '@plugnet/util'; - * - * numberToU8a(0x1234); // => [0x12, 0x34] - * ``` - */ -export default function numberToU8a (value?: number | null, bitLength: number = -1): Uint8Array { - if (!value || isNaN(value)) { - return new Uint8Array([]); - } - - return hexToU8a( - numberToHex(value, bitLength) - ); -} diff --git a/packages/util/src/polyfill/fill.spec.ts b/packages/util/src/polyfill/fill.spec.ts deleted file mode 100644 index 21cdce74db..0000000000 --- a/packages/util/src/polyfill/fill.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -describe('Array.fill', () => { - let arrayFill: any; - - beforeEach(() => { - arrayFill = Array.prototype.fill; - Array.prototype.fill = null as any; - - require('./fill'); - }); - - afterEach(() => { - Array.prototype.fill = arrayFill; - }); - - it('uses the polyfills', () => { - expect([1, 2, 3, 4, 5, 6, 7, 8].fill(5, 3)).toEqual([1, 2, 3, 5, 5, 5, 5, 5]); - }); -}); diff --git a/packages/util/src/polyfill/fill.ts b/packages/util/src/polyfill/fill.ts deleted file mode 100644 index b79316b16f..0000000000 --- a/packages/util/src/polyfill/fill.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -if (!Array.prototype.fill) { - Array.prototype.fill = function fill (value: any, start: number = 0, end?: number) { - // Steps 1-2. - if (!this) { - throw new TypeError('this is null or not defined'); - } - - const A = Object(this); - - // Steps 3-5. - const len = A.length >>> 0; - - // Steps 6-7. - const relativeStart = start >> 0; - - // Step 8. - let k = relativeStart < 0 - ? Math.max(len + relativeStart, 0) - : Math.min(relativeStart, len); - - // Steps 9-10. - const relativeEnd = end === undefined - ? len - : end >> 0; - - // Step 11. - const final = relativeEnd < 0 - ? Math.max(len + relativeEnd, 0) - : Math.min(relativeEnd, len); - - // Step 12. - while (k < final) { - A[k] = value; - k++; - } - - // Step 13. - return A; - }; -} - -if (!Uint8Array.prototype.fill) { - // @ts-ignore - Uint8Array.prototype.fill = Array.prototype.fill; -} diff --git a/packages/util/src/polyfill/index.ts b/packages/util/src/polyfill/index.ts deleted file mode 100644 index 8c7cff392a..0000000000 --- a/packages/util/src/polyfill/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import './fill'; -import './padEnd'; -import './padStart'; -import './setPrototypeOf'; -import './textDecoder'; -import './textEncoder'; diff --git a/packages/util/src/polyfill/padEnd.spec.ts b/packages/util/src/polyfill/padEnd.spec.ts deleted file mode 100644 index 8ae6c62958..0000000000 --- a/packages/util/src/polyfill/padEnd.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -describe('String padEnd', () => { - let stringEnd: (length: number, fill?: string) => string; - - beforeEach(() => { - stringEnd = String.prototype.padEnd; - - String.prototype.padEnd = null as any; - - require('./padEnd'); - }); - - afterEach(() => { - String.prototype.padEnd = stringEnd; - }); - - it('does padding', () => { - expect('test'.padEnd(8, 'A')).toEqual('testAAAA'); - expect('test'.padEnd(8)).toEqual('test '); - }); -}); diff --git a/packages/util/src/polyfill/padEnd.ts b/packages/util/src/polyfill/padEnd.ts deleted file mode 100644 index b1d4a888c3..0000000000 --- a/packages/util/src/polyfill/padEnd.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -if (!String.prototype.padEnd) { - String.prototype.padEnd = function padEnd (length: number, char: string = ' ') { - let result: string = String(this); - - while (result.length < length) { - result = result + char; - } - - return result; - }; -} diff --git a/packages/util/src/polyfill/padStart.spec.ts b/packages/util/src/polyfill/padStart.spec.ts deleted file mode 100644 index 175d82a4bc..0000000000 --- a/packages/util/src/polyfill/padStart.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -describe('String padStart', () => { - let stringStart: (length: number, fill?: string) => string; - - beforeEach(() => { - stringStart = String.prototype.padStart; - - String.prototype.padStart = null as any; - - require('./padStart'); - }); - - afterEach(() => { - String.prototype.padStart = stringStart; - }); - - it('does padding', () => { - expect('test'.padStart(8, 'A')).toEqual('AAAAtest'); - expect('test'.padStart(8)).toEqual(' test'); - }); -}); diff --git a/packages/util/src/polyfill/padStart.ts b/packages/util/src/polyfill/padStart.ts deleted file mode 100644 index b660dcac97..0000000000 --- a/packages/util/src/polyfill/padStart.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -if (!String.prototype.padStart) { - String.prototype.padStart = function padStart (length: number, char: string = ' ') { - let result: string = String(this); - - while (result.length < length) { - result = char + result; - } - - return result; - }; -} diff --git a/packages/util/src/polyfill/setPrototypeOf.ts b/packages/util/src/polyfill/setPrototypeOf.ts deleted file mode 100644 index e8fdf65dd3..0000000000 --- a/packages/util/src/polyfill/setPrototypeOf.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// React Native does not have Object.setPrototypeOf -if (!Object.setPrototypeOf) { - Object.setPrototypeOf = function (obj: any, proto: any) { - obj.__proto__ = proto; - - return obj; - }; -} diff --git a/packages/util/src/polyfill/textDecoder.spec.ts b/packages/util/src/polyfill/textDecoder.spec.ts deleted file mode 100644 index b2c62a814e..0000000000 --- a/packages/util/src/polyfill/textDecoder.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -describe('TextDecoder', () => { - let origTD: TextDecoder; - - beforeEach(() => { - origTD = (global as any).TextDecoder; - }); - - afterEach(() => { - (global as any).TextDecoder = origTD; - }); - - it('polyfills with no exceptions (without TextDecoder)', () => { - (global as any).TextDecoder = null; - - expect(require('./textDecoder')).toBeDefined(); - expect((global as any).TextDecoder).toBeDefined(); - }); - - it('polyfills with no exceptions (with TextDecoder)', () => { - (global as any).TextDecoder = require('util').TextDecoder; - - expect(require('./textDecoder')).toBeDefined(); - expect((global as any).TextDecoder).toBeDefined(); - }); -}); diff --git a/packages/util/src/polyfill/textDecoder.ts b/packages/util/src/polyfill/textDecoder.ts deleted file mode 100644 index 6a0f8626d2..0000000000 --- a/packages/util/src/polyfill/textDecoder.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// tslint:disable-next-line -if (typeof TextDecoder === 'undefined') { - try { - // @ts-ignore - global.TextDecoder = require('util').TextDecoder; - } catch (error) { - // noop - } -} diff --git a/packages/util/src/polyfill/textEncoder.spec.ts b/packages/util/src/polyfill/textEncoder.spec.ts deleted file mode 100644 index ef09a7ad9f..0000000000 --- a/packages/util/src/polyfill/textEncoder.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -describe('TextEncoder', () => { - let origTE: TextEncoder; - - beforeEach(() => { - origTE = (global as any).TextEncoder; - }); - - afterEach(() => { - (global as any).TextEncoder = origTE; - }); - - it('polyfills with no exceptions (without TextEncoder)', () => { - (global as any).TextEncoder = null; - - expect(require('./textEncoder')).toBeDefined(); - expect((global as any).TextEncoder).toBeDefined(); - }); - - it('polyfills with no exceptions (with TextEncoder)', () => { - (global as any).TextEncoder = require('util').TextEncoder; - - expect(require('./textEncoder')).toBeDefined(); - expect((global as any).TextEncoder).toBeDefined(); - }); -}); diff --git a/packages/util/src/polyfill/textEncoder.ts b/packages/util/src/polyfill/textEncoder.ts deleted file mode 100644 index 8fe6a76e10..0000000000 --- a/packages/util/src/polyfill/textEncoder.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -// tslint:disable-next-line -if (typeof TextEncoder === 'undefined') { - try { - // @ts-ignore For the Node.js case - global.TextEncoder = require('util').TextEncoder; - } catch (error) { - // noop - } -} diff --git a/packages/util/src/promisify.spec.ts b/packages/util/src/promisify.spec.ts deleted file mode 100644 index d7bdbdb5e1..0000000000 --- a/packages/util/src/promisify.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { promisify } from '.'; - -describe('promisify', () => { - it('handles functions with no parameters (resolve)', () => { - const fn = (cb: Function) => cb(null, [true, 'test', 1]); - - return promisify(null, fn).then((result) => { - expect(result).toEqual([true, 'test', 1]); - }); - }); - - it('handles functions with no parameters (reject)', () => { - const fn = (cb: Function) => cb(new Error('test reject')); - - return promisify(null, fn).catch((error) => { - expect(error.message).toEqual('test reject'); - }); - }); - - it('handles functions with parameters (resolve)', () => { - const fn = (a: any, b: any, c: any, cb: Function) => cb(null, [a, b, c]); - - return promisify(null, fn, 2, false, null).then((result) => { - expect(result).toEqual([2, false, null]); - }); - }); - - it('handles functions with parameters (reject)', () => { - const fn = (a: any, b: any, c: any, cb: Function) => cb(new Error(`test reject: ${a},${b},${c}`)); - - return promisify(null, fn, 3, 'string', true).catch((error) => { - expect(error.message).toEqual('test reject: 3,string,true'); - }); - }); - - it('applies the correct this argument', () => { - const self = { something: 'something' }; - - return promisify(self, function (cb: Function) { - // @ts-ignore - expect(this).toEqual(self); - cb(); - }); - }); -}); diff --git a/packages/util/src/promisify.ts b/packages/util/src/promisify.ts deleted file mode 100644 index ace314eaee..0000000000 --- a/packages/util/src/promisify.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name promisify - * @summary Wraps an async callback into a `Promise` - * @description - * Wraps the supplied async function `fn` that has a standard JS callback `(error: Error, result: any)` into a `Promise`, passing the supplied parameters. When `error` is set, the Promise is rejected, else the Promise resolves with the `result` value. - * @example - *
- * - * ```javascript - * const { promisify } from '@plugnet/util'; - * - * await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true` - * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!` - * ``` - */ -export default function promisify (self: any, fn: Function, ...params: Array): Promise { - return new Promise((resolve, reject) => { - fn.apply(self, params.concat([ - (error: Error | null, result: any): void => { - if (error) { - reject(error); - } else { - resolve(result); - } - } - ])); - }); -} diff --git a/packages/util/src/string/camelCase.spec.ts b/packages/util/src/string/camelCase.spec.ts deleted file mode 100644 index bdb6e28973..0000000000 --- a/packages/util/src/string/camelCase.spec.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringCamelCase } from '.'; - -describe('stringCamelCase', () => { - it('works correctly', () => { - expect( - stringCamelCase('Snake_case') - ).toBe('snakeCase'); - }); -}); diff --git a/packages/util/src/string/camelCase.ts b/packages/util/src/string/camelCase.ts deleted file mode 100644 index 771553f082..0000000000 --- a/packages/util/src/string/camelCase.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import stringCamelCase from 'camelcase'; - -export default stringCamelCase; diff --git a/packages/util/src/string/index.ts b/packages/util/src/string/index.ts deleted file mode 100644 index a7857759d6..0000000000 --- a/packages/util/src/string/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods to convert to work with `string` values - */ - -export { default as stringCamelCase } from './camelCase'; -export { default as stringLowerFirst } from './lowerFirst'; -export { default as stringShorten } from './shorten'; -export { default as stringToU8a } from './toU8a'; -export { default as stringUpperFirst } from './upperFirst'; diff --git a/packages/util/src/string/lowerFirst.spec.ts b/packages/util/src/string/lowerFirst.spec.ts deleted file mode 100644 index a777db7078..0000000000 --- a/packages/util/src/string/lowerFirst.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringLowerFirst } from '.'; - -describe('stringLowerFirst', () => { - it("lowers the first letter if it's a capital letter", () => { - expect( - stringLowerFirst('ABC') - ).toBe('aBC'); - }); - - it("lowers the first letter if it's a lowercase letter", () => { - expect( - stringLowerFirst('abc') - ).toBe('abc'); - }); - - it('returns undefined as empty', () => { - expect( - stringLowerFirst() - ).toBe(''); - }); - - it('returns null as empty', () => { - expect( - stringLowerFirst(null) - ).toBe(''); - }); -}); diff --git a/packages/util/src/string/lowerFirst.ts b/packages/util/src/string/lowerFirst.ts deleted file mode 100644 index 7f2d90aa5f..0000000000 --- a/packages/util/src/string/lowerFirst.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name stringLowerFirst - * @summary Lowercase the first letter of a string - * @description - * Lowercase the first letter of a string - * @example - *
- * - * ```javascript - * import { stringLowerFirst } from '@plugnet/util'; - * - * stringLowerFirst('ABC'); // => 'aBC' - * ``` - */ -export default function stringLowerFirst (value?: string | null): string { - if (!value) { - return ''; - } - - return value.charAt(0).toLowerCase() + value.slice(1); -} diff --git a/packages/util/src/string/shorten.spec.ts b/packages/util/src/string/shorten.spec.ts deleted file mode 100644 index 7783dd5afa..0000000000 --- a/packages/util/src/string/shorten.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringShorten } from '.'; - -describe('stringShorten', () => { - it('returns the value as-is when <= maxLength', () => { - expect( - stringShorten('0123456789', 4) - ).toEqual('0123456789'); - }); - - it('returns the shortened value when > maxLength', () => { - expect( - stringShorten('0123456789', 3) - ).toEqual('012..789'); - }); - - it('returns undefined as undefined', () => { - expect( - stringShorten() - ).toEqual('undefined'); - }); - - it('returns non-string values as strings', () => { - expect( - stringShorten(12345678, 2) - ).toEqual('12..78'); - }); -}); diff --git a/packages/util/src/string/shorten.ts b/packages/util/src/string/shorten.ts deleted file mode 100644 index e1e7ffef67..0000000000 --- a/packages/util/src/string/shorten.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name stringShorten - * @summary Returns a string with maximum length - * @description - * Checks the string against the `prefixLength`, if longer than dopuble this, shortens it by placing `..` in the middle of it - * @example - *
- * - * ```javascript - * import { stringShorten } from '@plugnet/util'; - * - * stringShorten('1234567890', 2); // => 12..90 - * ``` - */ -export default function stringShorten (_value?: any, prefixLength: number = 6): string { - const value = `${_value}`; - - if (value.length <= 2 + 2 * prefixLength) { - return value; - } - - return `${value.substr(0, prefixLength)}..${value.slice(-prefixLength)}`; -} diff --git a/packages/util/src/string/toU8a.spec.ts b/packages/util/src/string/toU8a.spec.ts deleted file mode 100644 index 5f906a9c99..0000000000 --- a/packages/util/src/string/toU8a.spec.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringToU8a } from '..'; - -describe('stringToU8a', () => { - it('decodes to an empty string for undefined', () => { - expect( - stringToU8a() - ).toEqual(new Uint8Array([])); - }); - - it('encodes the string correctly', () => { - expect( - stringToU8a('Привет, мир!') - ).toEqual( - new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33]) - ); - }); -}); diff --git a/packages/util/src/string/toU8a.ts b/packages/util/src/string/toU8a.ts deleted file mode 100644 index 99a0bf8527..0000000000 --- a/packages/util/src/string/toU8a.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -let encoder: { encode: (value: string) => Uint8Array }; - -function polyfilledEncode (value: string): Uint8Array { - const u8a = new Uint8Array(value.length); - - for (let i = 0; i < value.length; i++) { - u8a[i] = value.charCodeAt(i); - } - - return u8a; -} - -try { - encoder = new TextEncoder(); -} catch (error) { - encoder = { - encode: polyfilledEncode - }; -} - -/** - * @name stringToU8a - * @summary Creates a Uint8Array object from a utf-8 string. - * @description - * String input values return the actual encoded `UInt8Array`. `null` or `undefined` values returns an empty encoded array. - * @example - *
- * - * ```javascript - * import { stringToU8a } from '@plugnet/util'; - * - * stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f] - * ``` - */ -export default function stringToU8a (value?: string): Uint8Array { - if (!value) { - return new Uint8Array([]); - } - - return encoder.encode(value); -} diff --git a/packages/util/src/string/upperFirst.spec.ts b/packages/util/src/string/upperFirst.spec.ts deleted file mode 100644 index ba6920ccff..0000000000 --- a/packages/util/src/string/upperFirst.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { stringUpperFirst } from '.'; - -describe('stringUpperFirst', () => { - it("uppers the first letter if it's a capital letter", () => { - expect( - stringUpperFirst('ABC') - ).toBe('ABC'); - }); - - it("uppers the first letter if it's a lowercase letter", () => { - expect( - stringUpperFirst('abc') - ).toBe('Abc'); - }); - - it('returns undefined as empty', () => { - expect( - stringUpperFirst() - ).toBe(''); - }); - - it('returns null as empty', () => { - expect( - stringUpperFirst(null) - ).toBe(''); - }); -}); diff --git a/packages/util/src/string/upperFirst.ts b/packages/util/src/string/upperFirst.ts deleted file mode 100644 index f9d106ffb5..0000000000 --- a/packages/util/src/string/upperFirst.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name stringUpperFirst - * @summary Lowercase the first letter of a string - * @description - * Lowercase the first letter of a string - * @example - *
- * - * ```javascript - * import { stringUpperFirst } from '@plugnet/util'; - * - * stringUpperFirst('abc'); // => 'Abc' - * ``` - */ -export default function stringUpperFirst (value?: string | null): string { - if (!value) { - return ''; - } - - return value.charAt(0).toUpperCase() + value.slice(1); -} diff --git a/packages/util/src/types.ts b/packages/util/src/types.ts deleted file mode 100644 index 3dd36e1a1b..0000000000 --- a/packages/util/src/types.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -export interface ExtErrorInterface { - code: number; - data: any; - message: string; - stack: string; -} - -type Logger$Data$Fn = () => Array; -export type Logger$Data = Array; - -export type Logger = { - debug: (...values: Logger$Data) => void, - error: (...values: Logger$Data) => void, - log: (...values: Logger$Data) => void, - noop: (...values: Logger$Data) => void, - warn: (...values: Logger$Data) => void -}; - -export interface ToBnOptions { - isLe?: boolean; - isNegative?: boolean; -} diff --git a/packages/util/src/u8a/concat.spec.ts b/packages/util/src/u8a/concat.spec.ts deleted file mode 100644 index 4665fbb444..0000000000 --- a/packages/util/src/u8a/concat.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aConcat } from '.'; - -describe('u8aConcat', () => { - it('concatenates arrays', () => { - expect( - u8aConcat( - new Uint8Array([1, 2, 3, 4]), - new Uint8Array([5, 6]), - new Uint8Array([7, 8, 9]) - ) - ).toEqual( - new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]) - ); - }); - - it('concatenates arrays & hex values', () => { - expect( - u8aConcat( - new Uint8Array([1, 2, 3, 4]), - '0x0506', - '0x070809' - ) - ).toEqual( - new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]) - ); - }); -}); diff --git a/packages/util/src/u8a/concat.ts b/packages/util/src/u8a/concat.ts deleted file mode 100644 index c6b1a75829..0000000000 --- a/packages/util/src/u8a/concat.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import u8aToU8a from './toU8a'; - -/** - * @name u8aConcat - * @summary Creates a concatenated Uint8Array from the inputs. - * @description - * Concatenates the input arrays into a single `UInt8Array`. - * @example - *
- * - * ```javascript - * import { u8aConcat } from '@plugnet/util'; - * - * u8aConcat( - * new Uint8Array([1, 2, 3]), - * new Uint8Array([4, 5, 6]) - * ); // [1, 2, 3, 4, 5, 6] - * ``` - */ -export default function u8aConcat (..._list: Array): Uint8Array { - const list: Array = _list.map(u8aToU8a); - const length = list.reduce((total, item) => total + item.length, 0); - const result = new Uint8Array(length); - let offset = 0; - - return list.reduce((result, item) => { - result.set(item, offset); - offset += item.length; - - return result; - }, result); -} diff --git a/packages/util/src/u8a/fixLength.spec.ts b/packages/util/src/u8a/fixLength.spec.ts deleted file mode 100644 index 4b2c435a2b..0000000000 --- a/packages/util/src/u8a/fixLength.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aFixLength } from '.'; - -describe('u8aFixLength', () => { - it('returns bitLength === -1 as-is', () => { - expect( - u8aFixLength( - new Uint8Array([0x12, 0x34, 0x56, 0x78]) - ) - ).toEqual(new Uint8Array([0x12, 0x34, 0x56, 0x78])); - }); - - it('does not change when bitlength === length', () => { - expect( - u8aFixLength(new Uint8Array([0x12, 0x34, 0x56, 0x78]), 32) - ).toEqual(new Uint8Array([0x12, 0x34, 0x56, 0x78])); - }); - - it('trims values when bitLength > length', () => { - expect( - u8aFixLength(new Uint8Array([0x12, 0x34, 0x56, 0x78]), 16) - ).toEqual(new Uint8Array([0x12, 0x34])); - }); - - it('adds zeros when bitLength < length (withPadded)', () => { - expect( - u8aFixLength(new Uint8Array([0x12, 0x34]), 32) - ).toEqual(new Uint8Array([0, 0, 0x12, 0x34])); - }); -}); diff --git a/packages/util/src/u8a/fixLength.ts b/packages/util/src/u8a/fixLength.ts deleted file mode 100644 index 00e6b10319..0000000000 --- a/packages/util/src/u8a/fixLength.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name u8aFixLength - * @summary Shifts a Uint8Array to a specific bitLength - * @description - * Returns a uint8Array with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. - * @example - *
- * - * ```javascript - * import { u8aFixLength } from '@plugnet/util'; - * - * u8aFixLength('0x12') // => 0x12 - * u8aFixLength('0x12', 16) // => 0x0012 - * u8aFixLength('0x1234', 8) // => 0x12 - * ``` - */ -export default function u8aFixLength (value: Uint8Array, bitLength: number = -1, atStart: boolean = false): Uint8Array { - const byteLength = Math.ceil(bitLength / 8); - - if (bitLength === -1 || value.length === byteLength) { - return value; - } - - if (value.length > byteLength) { - return value.subarray(0, byteLength); - } - - const result = new Uint8Array(byteLength); - - if (atStart) { - result.set(value, 0); - } else { - result.set(value, byteLength - value.length); - } - - return result; -} diff --git a/packages/util/src/u8a/index.ts b/packages/util/src/u8a/index.ts deleted file mode 100644 index 2ffdab6b8e..0000000000 --- a/packages/util/src/u8a/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @summary Utility methods to convert to and from `Uint8Array` objects - */ - -export { default as u8aConcat } from './concat'; -export { default as u8aFixLength } from './fixLength'; -export { default as u8aToBn } from './toBn'; -export { default as u8aToBuffer } from './toBuffer'; -export { default as u8aToHex } from './toHex'; -export { default as u8aToString } from './toString'; -export { default as u8aToU8a } from './toU8a'; diff --git a/packages/util/src/u8a/toBn.spec.ts b/packages/util/src/u8a/toBn.spec.ts deleted file mode 100644 index 172a485dba..0000000000 --- a/packages/util/src/u8a/toBn.spec.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToBn } from '.'; - -describe('u8aToBn', () => { - it('converts little-endian by default', () => { - expect( - u8aToBn( - new Uint8Array([0x12, 0x34]) - ).toString(16) - ).toBe('3412'); - }); - it('converts values (big-endian)', () => { - expect( - u8aToBn( - new Uint8Array([0x12, 0x34]), - { isLe: false } - ).toString(16) - ).toBe('1234'); - }); - - it('converts values (little-endian)', () => { - expect( - u8aToBn( - new Uint8Array([0x12, 0x34]), - { isLe: true } - ).toString(16) - ).toBe('3412'); - }); - - it('converts empty', () => { - expect( - u8aToBn( - new Uint8Array([]), - { isLe: true } - ).toString(16) - ).toBe('0'); - }); - - it('handles negative numbers (little-endian)', () => { - expect( - u8aToBn( - new Uint8Array([46, 251]), - { isLe: true, isNegative: true } - ).toNumber() - ).toBe(-1234); - }); - - it('handles negative numbers (big-endian)', () => { - expect( - u8aToBn( - new Uint8Array([251, 46]), - { isLe: false, isNegative: true } - ).toNumber() - ).toBe(-1234); - }); - - it('handles overflows correctly (little-endian)', () => { - expect( - u8aToBn( - new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), - { isLe: true } - ).toNumber() - ).toBe(256); - }); - - it('handles backward compatibility)', () => { - expect( - u8aToBn( - new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), - false - ).eq( - u8aToBn( - new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), - { isLe: false } - ) - ) - ).toBe(true); - expect( - u8aToBn( - new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), - true - ).eq( - u8aToBn( - new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), - { isLe: true } - ) - ) - ).toBe(true); - }); -}); diff --git a/packages/util/src/u8a/toBn.ts b/packages/util/src/u8a/toBn.ts deleted file mode 100644 index 6a35fd3333..0000000000 --- a/packages/util/src/u8a/toBn.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import BN from 'bn.js'; - -import hexToBn from '../hex/toBn'; -import u8aToHex from './toHex'; -import { ToBnOptions } from '../types'; - -/** - * @name u8aToBn - * @summary Creates a BN from a Uint8Array object. - * @description - * `UInt8Array` input values return the actual BN. `null` or `undefined` values returns an `0x0` value. - * @param value The value to convert - * @param options Options to pass while converting - * @param options.isLe Convert using Little Endian - * @param options.isNegative Convert using two's complement - * @example - *
- * - * ```javascript - * import { u8aToBn } from '@plugnet/util'; - * - * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f - * ``` - */ -export default function u8aToBn ( - value: Uint8Array, - options: ToBnOptions | boolean = { isLe: true, isNegative: false } -): BN { - return hexToBn( - u8aToHex(value), - options - ); -} diff --git a/packages/util/src/u8a/toBuffer.spec.ts b/packages/util/src/u8a/toBuffer.spec.ts deleted file mode 100644 index 9e67ad37b4..0000000000 --- a/packages/util/src/u8a/toBuffer.spec.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToBuffer } from '.'; - -describe('u8aToBuffer', () => { - it('returns [] when the buffer is null', () => { - expect( - u8aToBuffer(null) - ).toEqual(Buffer.from([])); - }); - - it('returns the Buffer value for the Uint8Array', () => { - expect( - u8aToBuffer(new Uint8Array([128, 0, 10])) - ).toEqual(Buffer.from([128, 0, 10])); - }); -}); diff --git a/packages/util/src/u8a/toBuffer.ts b/packages/util/src/u8a/toBuffer.ts deleted file mode 100644 index b938f88c9f..0000000000 --- a/packages/util/src/u8a/toBuffer.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -/** - * @name u8aToBuffer - * @summary Creates a Buffer object from a hex string. - * @description - * `null` inputs returns an empty `Buffer` result. `UInt8Array` input values return the actual bytes value converted to a `Buffer`. Anything that is not a `UInt8Array` throws an error. - * @example - *
- * - * ```javascript - * import { u8aToBuffer } from '@plugnet/util'; - * - * console.log('Buffer', u8aToBuffer('0x123480001f')); - * ``` - */ -export default function u8aToBuffer (value?: Uint8Array | null): Buffer { - if (!value) { - return Buffer.from([]); - } - - // @ts-ignore yes, from also works with u8a - return Buffer.from(value); -} diff --git a/packages/util/src/u8a/toHex.spec.ts b/packages/util/src/u8a/toHex.spec.ts deleted file mode 100644 index 17575d4aa6..0000000000 --- a/packages/util/src/u8a/toHex.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToHex } from '.'; - -describe('u8aToHex', () => { - it('returns empty as 0x', () => { - expect( - u8aToHex() - ).toEqual('0x'); - }); - - it('returns empty as "" (unprefixed)', () => { - expect( - u8aToHex(null, -1, false) - ).toEqual(''); - }); - - it('returns the hex value for the array', () => { - expect( - u8aToHex( - new Uint8Array([128, 0, 10]) - ) - ).toEqual('0x80000a'); - }); - - it('returns the hex value for the array (unprefixed)', () => { - expect( - u8aToHex( - new Uint8Array([128, 0, 10]), - -1, false - ) - ).toEqual('80000a'); - }); - - it('handles starting zeros correctly', () => { - expect( - u8aToHex( - new Uint8Array([ 0, 1, 0, 0, 0, 0, 0, 0 ]) - ) - ).toEqual('0x0001000000000000'); - }); - - it('returns the hex value where allowed < max', () => { - expect( - u8aToHex( - new Uint8Array(Uint8Array.from([128, 0, 10, 11]), 64) - ) - ).toEqual('0x80000a0b'); - }); - - it('returns the trimmed hex value where allowed >= max', () => { - expect( - u8aToHex( - new Uint8Array([128, 0, 10, 11, 12, 13]), - 32 - ) - ).toEqual('0x8000…0c0d'); - }); -}); diff --git a/packages/util/src/u8a/toHex.ts b/packages/util/src/u8a/toHex.ts deleted file mode 100644 index b95119b77f..0000000000 --- a/packages/util/src/u8a/toHex.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -const ALPHABET = '0123456789abcdef'; - -/** - * @name u8aToHex - * @summary Creates a hex string from a Uint8Array object. - * @description - * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string. - * @example - *
- * - * ```javascript - * import { u8aToHex } from '@plugnet/util'; - * - * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f - * ``` - */ -export default function u8aToHex (value?: Uint8Array | null, bitLength: number = -1, isPrefixed: boolean = true): string { - const prefix = isPrefixed - ? '0x' - : ''; - - if (!value || !value.length) { - return prefix; - } - - const byteLength = Math.ceil(bitLength / 8); - - if (byteLength > 0 && value.length > byteLength) { - const halfLength = Math.ceil(byteLength / 2); - - return `${u8aToHex(value.subarray(0, halfLength), -1, isPrefixed)}…${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`; - } - - // based on comments in https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex and - // implementation in http://jsben.ch/Vjx2V - optimisation here suggests that a forEach loop is faster - // than reduce as well (clocking at in 90% of the reduce speed with tweaking in the playpen above) - return value.reduce((result, value) => { - return result + ALPHABET[value >> 4] + ALPHABET[value & 15]; - }, prefix); -} diff --git a/packages/util/src/u8a/toString.spec.ts b/packages/util/src/u8a/toString.spec.ts deleted file mode 100644 index c0ebc9d3c0..0000000000 --- a/packages/util/src/u8a/toString.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToString } from '..'; - -describe('u8aToString', () => { - it('decodes to an empty string for undefined', () => { - expect( - u8aToString() - ).toEqual(''); - }); - - it('decodes to an empty string for empty buffer', () => { - expect( - u8aToString(new Uint8Array([])) - ).toEqual(''); - }); - - it('decodes the buffer correctly', () => { - expect( - u8aToString( - new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33]) - ) - ).toEqual('Привет, мир!'); - }); -}); diff --git a/packages/util/src/u8a/toString.ts b/packages/util/src/u8a/toString.ts deleted file mode 100644 index e8467a2626..0000000000 --- a/packages/util/src/u8a/toString.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -let decoder: { decode: (value: Uint8Array) => string }; - -function polyfilledDecode (value: Uint8Array): string { - return value.reduce((str, code) => { - return str + String.fromCharCode(code); - }, ''); -} - -try { - decoder = new TextDecoder('utf-8'); -} catch (error) { - decoder = { - decode: polyfilledDecode - }; -} - -/** - * @name u8aToString - * @summary Creates a utf-8 string from a Uint8Array object. - * @description - * `UInt8Array` input values return the actual decoded utf-8 string. `null` or `undefined` values returns an empty string. - * @example - *
- * - * ```javascript - * import { u8aToString } from '@plugnet/util'; - * - * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello - * ``` - */ -export default function u8aToString (value?: Uint8Array | null): string { - if (!value || !value.length) { - return ''; - } - - return decoder.decode(value); -} diff --git a/packages/util/src/u8a/toU8a.spec.ts b/packages/util/src/u8a/toU8a.spec.ts deleted file mode 100644 index df4eed5a61..0000000000 --- a/packages/util/src/u8a/toU8a.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { u8aToU8a } from '.'; - -describe('u8aToU8a', () => { - it('returns an empty Uint8Array when null provided', () => { - expect( - u8aToU8a(null) - ).toHaveLength(0); - }); - - it('returns a Uint8Array (hex input)', () => { - expect( - u8aToU8a('0x80000a') - ).toEqual( - new Uint8Array([128, 0, 10]) - ); - }); - - it('returns Uint8Array (string input)', () => { - expect( - u8aToU8a('abcde fghij') - ).toEqual(new Uint8Array([97, 98, 99, 100, 101, 32, 102, 103, 104, 105, 106])); - }); - - it('returns a Uint8Array (buffer input)', () => { - expect( - u8aToU8a(Buffer.from('80000a', 'hex')) - ).toEqual( - new Uint8Array([128, 0, 10]) - ); - }); - - it('creates from Array', () => { - expect( - u8aToU8a([128, 0, 10, 11, 12]) - ).toEqual( - new Uint8Array([128, 0, 10, 11, 12]) - ); - }); - - it('returns a Uint8Array as-is (u8a input)', () => { - expect( - u8aToU8a(new Uint8Array([128, 0, 10])) - ).toEqual( - new Uint8Array([128, 0, 10]) - ); - }); -}); diff --git a/packages/util/src/u8a/toU8a.ts b/packages/util/src/u8a/toU8a.ts deleted file mode 100644 index 1224013c3c..0000000000 --- a/packages/util/src/u8a/toU8a.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017-2019 @polkadot/util authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import isBuffer from '../is/buffer'; -import isHex from '../is/hex'; -import isString from '../is/string'; -import bufferToU8a from '../buffer/toU8a'; -import hexToU8a from '../hex/toU8a'; -import stringToU8a from '../string/toU8a'; - -/** - * @name u8aToU8a - * @summary Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input. - * @description - * `null` ior `undefined` nputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation. - * @example - *
- * - * ```javascript - * import { u8aToU8a } from '@plugnet/util'; - * - * u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34]) - * u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34]) - * ``` - */ -export default function u8aToU8a (value?: Array | Buffer | Uint8Array | string | null): Uint8Array { - if (!value) { - return new Uint8Array(); - } - - if (isBuffer(value)) { - return bufferToU8a(value); - } - - if (isString(value)) { - return isHex(value) - ? hexToU8a(value) - : stringToU8a(value); - } - - if (Array.isArray(value)) { - return Uint8Array.from(value); - } - - return value; -} diff --git a/tsconfig.json b/tsconfig.json index 1daa4279ee..e956c6b00d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,13 +22,7 @@ "@plugnet/storage": ["packages/type-storage/src"], "@plugnet/storage/*": ["packages/type-storage/src/*"], "@plugnet/types": ["packages/types/src"], - "@plugnet/types/*": ["packages/types/src/*"], - "@plugnet/keyring": ["packages/keyring/src"], - "@plugnet/keyring/*": ["packages/keyring/src/*"], - "@plugnet/util": ["packages/util/src"], - "@plugnet/util/*": ["packages/util/src/*"], - "@plugnet/util-crypto": ["packages/util-crypto/src"], - "@plugnet/util-crypto/*": ["packages/util-crypto/src/*"] + "@plugnet/types/*": ["packages/types/src/*"] }, "typeRoots": [ "./node_modules/@polkadot/ts",