Compare commits

...

663 Commits

Author SHA1 Message Date
wltsmrz
fd0dc3b330 Merge pull request #108 from shekenahglory/develop
[FIX] vault client: rippleTxt test request diverted to offline mock
2014-06-23 13:45:41 -07:00
Matthew Fettig
3ebcadfad4 [FIX] vault client: rippleTxt test request diverted to offline mock 2014-06-23 13:44:16 -07:00
wltsmrz
f963d266a2 Merge pull request #107 from geertweening/update_history
[DOC] update changelog with currency changes
2014-06-23 13:23:04 -07:00
shekenahglory
309957a6cf Update HISTORY.md 2014-06-23 13:16:19 -07:00
Geert Weening
47094f84d7 [DOC] update changelog with currency changes 2014-06-23 12:01:13 -07:00
wltsmrz
68c86bf672 Merge pull request #106 from shekenahglory/develop
[FIX] vault client: set SJCL test entropy random string to base64
2014-06-23 11:52:41 -07:00
Matthew Fettig
e6782f4563 [FIX] vault client: set SJCL test entropy random string to base64 2014-06-23 11:30:06 -07:00
wltsmrz
1b2b19381b Merge pull request #103 from shekenahglory/develop
[FEATURE] vault client: updateProfile and deleteBlob
2014-06-23 11:09:30 -07:00
wltsmrz
d495f397b0 Bump version 2014-06-23 10:58:48 -07:00
wltsmrz
f1a58de348 Update HISTORY.md 2014-06-23 10:58:36 -07:00
Matthew Fettig
6ae186951b [FEATURE] vault client: updateProfile and deleteBlob 2014-06-19 15:58:38 -07:00
wltsmrz
8d77ff9af7 Merge pull request #102 from shekenahglory/develop
Save encrypted blob decrypt key at login if missing
2014-06-18 21:35:16 -07:00
Matthew Fettig
eeb5e22e9a [FIX] blob: catch missing encrypted blob decrypt key 2014-06-18 17:16:40 -07:00
Matthew Fettig
fc5284cc88 [CHORE] RippleTxt: add tests for new functions 2014-06-18 16:40:55 -07:00
Matthew Fettig
6a7eb132bd [FEATURE] RippleTxt: parse ripple.txt for currencies 2014-06-18 16:28:18 -07:00
Matthew Fettig
f8519584d2 [CHORE] RippleTxt and AuthInfo changed from classes to objects
fix vault test entropy issue
refactor missing feilds on login
2014-06-18 12:36:33 -07:00
Matthew Fettig
58b307411e [FIX] vault client: account registration using lowercase version of username
also added username validation with rules from ripple trade client
2014-06-17 14:12:11 -07:00
Matthew Fettig
c7dd3cc70e [FIX] vault-test: increase entropy from randomBytes
When running vault-test.js alone, the entropy was insufficient
for the seed generator.  Entropy must be added elsewhere when
the full test suite is run.
2014-06-17 13:29:27 -07:00
Matthew Fettig
dc62dbe022 [FEATURE] vault client: create encrypted blob decrypt key if missing
if the key is missing, upon login the key will be automatically
generated and saved to the blobvault.
2014-06-17 13:20:28 -07:00
Vahe Hovhannisyan
e50ddd6237 [FIX] Blobvault: Include domain on account creation call
Blobvault now requires a domain field to be passed on the account creation request.
2014-06-16 15:43:34 -07:00
wltsmrz
6a55dbc55e Add build script 2014-06-16 13:02:52 -07:00
wltsmrz
4e7cf460ec Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-06-16 12:57:02 -07:00
wltsmrz
87dd8d535a Remove dedupe plugin from minified webpack build 2014-06-16 12:56:28 -07:00
wltsmrz
ce6010ecd3 Merge pull request #101 from shekenahglory/develop
Offline vault client tests and improved coverage
2014-06-14 17:13:02 -07:00
Matthew Fettig
ac5f146187 [CHORE] change randomBytes to 256 for vault test 2014-06-14 09:13:14 -07:00
Matthew Fettig
14b2697a52 [CHORE] use strict equal on vault tests 2014-06-14 09:01:35 -07:00
Matthew Fettig
a4078e10e9 [CHORE] vault client test for blob creation 2014-06-13 14:54:41 -07:00
Matthew Fettig
06796aa7c0 Merge branch 'feature/nock' into develop 2014-06-13 14:36:42 -07:00
Matthew Fettig
62d4be0185 [CHORE] offline tests for vault client 2014-06-13 14:35:37 -07:00
Matthew Fettig
2e0536ea2d bug fixes and documentation 2014-06-13 14:35:01 -07:00
Matthew Fettig
94c7408b5b [FEATURE] offline vault client tests 2014-06-12 17:46:34 -07:00
wltsmrz
1186b4a314 Fix fractional transaction fee 2014-06-12 03:06:23 -07:00
wltsmrz
1cccf01bf2 Merge pull request #99 from sublimator/develop
Test we don't compute floating point median Fee
2014-06-12 02:58:40 -07:00
sublimator
8f7cda3c2c testify 2014-06-12 16:22:19 +07:00
wltsmrz
c95ac13946 Merge pull request #98 from ripple/tests
Improve test coverage
2014-06-12 00:33:14 -07:00
wltsmrz
ee1ce36045 Use URL rather than hostname for setServer lookup 2014-06-12 00:29:23 -07:00
wltsmrz
a4f22d8b42 Improve transaction-test coverage 2014-06-12 00:20:56 -07:00
wltsmrz
2afce7cf54 Improve server-test coverage 2014-06-11 23:19:50 -07:00
wltsmrz
6150721951 Improve request-test coverage 2014-06-11 22:24:21 -07:00
wltsmrz
61b3ef0205 Merge pull request #96 from ripple/tests
Add server and transaction test
2014-06-11 21:44:28 -07:00
wltsmrz
06108ffee3 Fix server test 2014-06-11 21:40:41 -07:00
wltsmrz
726b309085 [THING] Add transaction test 2014-06-11 21:23:27 -07:00
wltsmrz
ff14b55ea5 Merge pull request #94 from shekenahglory/develop
Blob recover, change password, and refactoring
2014-06-11 16:32:25 -07:00
Matthew Fettig
bb82eb9219 [BUG] fix bug on update blob keys 2014-06-11 16:10:24 -07:00
Matthew Fettig
abc43f80e0 Merge vault client refactoring 2014-06-11 15:54:58 -07:00
Matthew Fettig
f6343dc1d1 [CHORE] refactor vault client functions 2014-06-11 15:51:59 -07:00
Matthew Fettig
182e1863f4 [FEATURE] recover blob and change password 2014-06-11 09:26:03 -07:00
Vahe Hovhannisyan
0a8d4ad587 Blobvault: Ripple name change. 2014-06-10 16:14:20 -07:00
wltsmrz
48e49ac42b Fix server test 2014-06-10 15:15:56 -07:00
wltsmrz
1579d58edf [THING] Add server test 2014-06-09 13:03:02 -07:00
wltsmrz
61cb21188d Merge pull request #93 from geertweening/fix/amount_regex
[FIX] decimal precision amount parsing
2014-06-05 14:50:34 -07:00
Geert Weening
49d50c02d4 [FIX] decimal precision amount parsing
- add non-grouping operator to regex
- add tests to cover the problematic cases
2014-06-05 14:14:50 -07:00
wltsmrz
b7f7e6dc60 Merge pull request #92 from ripple/tests
Update tests
2014-06-04 18:10:13 -07:00
wltsmrz
e49bb4e527 Update tests 2014-06-04 18:04:57 -07:00
wltsmrz
44a9724b2a Merge pull request #91 from shekenahglory/develop
Necessary updates for vault client integration in ripple trade
2014-06-04 17:41:29 -07:00
Matthew Fettig
7af4a376a2 [CHORE] lint cleanup 2014-06-04 15:14:05 -07:00
Matthew Fettig
77e69efe19 [FEATURE] blobvault: resend email verification 2014-06-04 15:09:22 -07:00
Matthew Fettig
da8061ed52 [FEATURE] expose AuthInfo and RippleTxt modules in ripple class 2014-06-04 15:08:08 -07:00
Matthew Fettig
90d65573b5 Merge remote-tracking branch 'upstream/develop' into develop 2014-06-04 11:51:52 -07:00
wltsmrz
838180a498 Merge pull request #89 from ripple/multi-server
Multi-server update
2014-06-04 11:47:02 -07:00
Matthew Fettig
5ebab2fe28 [CHORE] refactored identity functions necessary for ripple client integration 2014-06-04 10:45:05 -07:00
Matthew Fettig
0ff0004d42 Merge remote-tracking branch 'upstream/develop' into develop 2014-06-04 10:03:17 -07:00
wltsmrz
b931b92773 Merge pull request #90 from geertweening/feature/iso_code
[FEATURE] add getter for a Currency's iso_code
2014-06-03 16:50:12 -07:00
wltsmrz
ad08e20085 Cleanup 2014-06-03 16:44:36 -07:00
wltsmrz
c1c18c465d Use median rather than average transaction fee 2014-06-03 16:36:18 -07:00
Geert Weening
a71fc07ba5 [FEATURE] add getter for a Currency's iso_code 2014-06-03 15:18:45 -07:00
Matthew Fettig
89c4839fa5 [DEBUG] multiple bug fixes with blob creation 2014-06-03 14:06:15 -07:00
wltsmrz
41ee43740e Merge pull request #88 from justmoon/feature/generate_ledger_entry_indexes
Generate ledger entry indexes
2014-06-03 13:41:08 -07:00
wltsmrz
179c215b15 Uncomment reconnect logic 2014-06-03 13:36:06 -07:00
Stefan Thomas
9100e8ecc0 [FEATURE] Add ability to calculate ledger entry keys. 2014-06-04 00:12:10 +04:00
Stefan Thomas
fb213e5818 [CHORE] Move HTTP request signing functionality into its own class. 2014-06-04 00:12:06 +04:00
Matthew Fettig
ac12e3fb5c Merge remote-tracking branch 'upstream/develop' into develop 2014-06-03 13:03:20 -07:00
wltsmrz
caa78b11dd Merge pull request #87 from geertweening/feature/numeric_currency_code
[FEATURE] support numeric currency codes
2014-06-03 12:21:24 -07:00
Geert Weening
61586a4185 [FEATURE] support numeric currency codes
ISO 4217 states support for both alphabetic and numeric codes. rippled adheres to the ISO 4217 as stated in the Currency_Format on the wiki (https://ripple.com/wiki/Currency_Format) and there are trustlines out there with numeric currency codes.

The three-digit numeric code is useful when currency codes need to be understood in countries that do not use Latin scripts and for computerised systems. Where possible the 3 digit numeric code is the same as the numeric country code.
2014-06-02 17:14:22 -07:00
wltsmrz
a7df5248c9 Broadcast transaction submission requests, use average server fee 2014-06-02 17:11:46 -07:00
wltsmrz
cf53ec9da8 Merge pull request #83 from geertweening/feature-demurrage
Interest bearing currency parsing support
2014-06-02 12:52:15 -07:00
Matthew Fettig
46e966fb7f Merge remote-tracking branch 'upstream/develop' into develop 2014-06-02 09:17:14 -07:00
Matthew Fettig
01e38ed4ca [BUG] merge IE11 signature fix 2014-06-02 09:16:48 -07:00
wltsmrz
01459061ee Merge pull request #86 from shekenahglory/develop
Identity functions for blob vault storage
2014-05-30 15:55:42 -07:00
Geert Weening
3ef105e077 [FEATURE] support full_name in to_human() and to_json() 2014-05-30 15:10:07 -07:00
Geert Weening
decebe3d2e [FEATURE] allow numbers, hyphens and spaces in full currency 2014-05-30 15:10:07 -07:00
Geert Weening
2a832777a7 [TEST] add more from_number tests 2014-05-30 15:10:07 -07:00
Geert Weening
6a718c4384 [FIX] parse_number correctly setting _is_negative 2014-05-30 15:10:07 -07:00
Geert Weening
a1face76b7 [FIX] parse_number should create a non-native currency
"1" just means "some issuer, don't care which"
2014-05-30 15:10:07 -07:00
Geert Weening
8104f71162 [FIX] Currency by number default type
should be a non-interest bearing currency
2014-05-30 15:10:07 -07:00
Geert Weening
1ce2a517aa [TEST] update amount test for interest bearing currencies 2014-05-30 15:10:07 -07:00
Geert Weening
53c7836a7a [TEST] test human readable Currency parsing 2014-05-30 15:10:07 -07:00
Geert Weening
160b6e8a51 [FEATURE] human readable demurrage support
- human readable string to Currency
- Currency to human readable string
2014-05-30 15:10:07 -07:00
Geert Weening
b1f6284813 [CHORE] add IEEE-754 Double Precision float support
for an 8 byte representation of floats
2014-05-30 15:10:07 -07:00
Matthew Fettig
d104ebb6f5 [BUG] fix bug with nationalID types 2014-05-30 14:47:57 -07:00
Matthew Fettig
017713c435 [CHORE] merge upstream changes 2014-05-30 14:35:01 -07:00
wltsmrz
644ca2b472 Fix authinfo test 2014-05-30 13:45:14 -07:00
wltsmrz
453ff91065 Comma should be semicolon, woopsy 2014-05-30 13:30:48 -07:00
Matthew Fettig
8b79ec0e5a [DOCS] added Vault Client Documentation 2014-05-30 13:01:22 -07:00
Matthew Fettig
95b7858c8f [CHORE] require specific entity types 2014-05-30 13:00:41 -07:00
Matthew Fettig
5ef7e5462e Merge branch 'feature/best-practices' into develop 2014-05-30 11:54:41 -07:00
Matthew Fettig
54a2655bc2 [CHORE] gulp lint cleanup 2014-05-30 11:53:05 -07:00
Matthew Fettig
785a066ebb [CHORE] Crypt exported by name 2014-05-30 11:10:25 -07:00
Matthew Fettig
fa60b182a3 [CHORE] RippleTxt and AuthInfo exported by name 2014-05-30 10:57:00 -07:00
Matthew Fettig
dbc965de3c [CHORE] VaultClient exported by name 2014-05-30 10:52:57 -07:00
Matthew Fettig
77814b791d Merge branch 'feature/identity' into develop 2014-05-30 10:46:19 -07:00
Matthew Fettig
ddf12d43c3 [CHORE] BlobClient exported by name 2014-05-30 10:39:41 -07:00
Matthew Fettig
f5b59b4268 [FEATURE] tests for identity functions 2014-05-30 10:13:33 -07:00
Matthew Fettig
58e14f3bb3 [CHORE] limit identity to defined fields 2014-05-30 10:03:49 -07:00
wltsmrz
1c02166662 Fix server url formatting 2014-05-30 00:50:06 -07:00
Matthew Fettig
0e5c29269f [FEATURE] identity unset, getAll, getFullAddress 2014-05-29 17:52:27 -07:00
wltsmrz
9a349a3d55 Begin work on offline vault client tests 2014-05-29 14:33:53 -07:00
Matthew Fettig
d5e01adbf9 [FEATURE] identity get and set 2014-05-29 13:57:58 -07:00
wltsmrz
61bc01ae12 Cleanup 2014-05-29 06:46:54 -07:00
wltsmrz
c3568de8b3 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-05-28 18:23:11 -07:00
wltsmrz
eca5ac7611 Cleanup 2014-05-28 18:22:54 -07:00
wltsmrz
a8e0cb2e0b Merge pull request #82 from emoitzi/develop
[FIX] remote.getPendingTransactions sets _clientID now correctly
2014-05-28 12:38:31 -07:00
Matthew Fettig
799bb5faeb [CHORE] stubbed functions 2014-05-28 10:13:37 -07:00
Ewald Moitzi
0b5c0722e0 removed .only from remote testcase for pending transactions 2014-05-27 12:43:56 +02:00
Ewald Moitzi
3964e4522e [FIX] remote.getPendingTransactions sets _clientID now correctly
- added testcase for it
2014-05-27 12:27:28 +02:00
wltsmrz
bdb299e085 Merge branch 'multi-server' into develop 2014-05-23 12:27:09 -07:00
wltsmrz
349ca81cc9 Merge pull request #80 from geertweening/amount-regex
Amount regex
2014-05-21 10:57:46 -07:00
Geert Weening
77a323aaae [CHJORE] gitignore intellij files 2014-05-21 09:40:50 -07:00
Geert Weening
8be08b5e73 [DOC] regex breakdown for human parseble amount 2014-05-21 09:40:40 -07:00
Geert Weening
b53b05496d [CHORE] remove non-capturing group (?:)
it doesn't affect the matching, seems superfluous
2014-05-21 09:39:40 -07:00
wltsmrz
bd2dba7f15 Merge pull request #79 from shekenahglory/develop
Ripple Vault Client Integration
2014-05-21 00:43:45 -07:00
Matthew Fettig
81e0e2672d [CHORE] new example data 2014-05-20 16:47:15 -07:00
Matthew Fettig
bd65c6e6d0 Merge branch 'feature/vault-client' into develop 2014-05-20 15:57:21 -07:00
Matthew Fettig
396d7b07d8 [DOC] blob comments 2014-05-20 15:56:07 -07:00
Matthew Fettig
55184162d1 [DOC] crypt comments 2014-05-20 15:40:27 -07:00
Matthew Fettig
beffd0864a [FEATURE] register blob 2014-05-20 15:10:16 -07:00
Matthew Fettig
5ba7c31e4c [DOC] vault client comments 2014-05-20 13:40:05 -07:00
Matthew Fettig
b26129db72 [FEATURE] vault, blob, and crypt module 2014-05-20 13:01:51 -07:00
Matthew Fettig
1693a57845 [CHORE] update comments 2014-05-19 16:50:02 -07:00
Matthew Fettig
7ea1ba168d [FEATURE] authinfo module 2014-05-19 16:38:51 -07:00
Matthew Fettig
7fe530e82c [FEATURE] ripple.txt client 2014-05-19 16:00:53 -07:00
Matthew Fettig
7e4ae26b8f [CHORE] include superagent, vault-test 2014-05-19 15:25:53 -07:00
wltsmrz
963e1d58cb Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-05-19 12:08:08 -07:00
wltsmrz
cc6f683590 Fix merge conflicts 2014-05-19 12:07:24 -07:00
Nicholas Dudfield
da3af124ba Update SerializedObject.from_json tests 2014-05-19 15:04:24 +07:00
wltsmrz
b342cf1edf Rank servers in real-time (first pass), add JSDOc to Remote, cleanup 2014-05-18 08:39:47 -07:00
Nicholas Dudfield
a1989b3931 Tweak to parse_options 2014-05-18 17:37:54 +07:00
Nicholas Dudfield
80bdce970a Add binary <--> json encoding integration tests
* Add full json ledger dumps of ledgers 38129 and 40000 to test/fixtures
* Use `Ledger` to calculate account and transaction hashes and verify
  against dumps
2014-05-18 17:33:47 +07:00
wltsmrz
7cf80a468d Merge pull request #77 from justmoon/feature/coveralls
Switch to Istanbul for code coverage
2014-05-17 06:13:48 -07:00
Stefan Thomas
bee632e1e2 Re-enable Travis email notifications. 2014-05-17 10:00:01 +02:00
Stefan Thomas
7901e12b0a Switch to Istanbul for code coverage. Add coverage to CI via coveralls. 2014-05-17 09:59:20 +02:00
wltsmrz
8979a3cf02 Merge branch account-ids 2014-05-15 07:25:16 -07:00
wltsmrz
9025119f8d Typo, check that request callback is only called once 2014-05-15 07:00:04 -07:00
wltsmrz
fdaa63c132 Use mocha specification reporter 2014-05-15 03:02:39 -07:00
wltsmrz
9e825e927c Use Gulp build system 2014-05-15 02:59:06 -07:00
wltsmrz
4929d63073 Remove sinon require 2014-05-15 02:56:07 -07:00
wltsmrz
5b0dd33fa8 Lint 2014-05-15 00:58:09 -07:00
wltsmrz
5203a1e868 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-05-14 01:29:38 -07:00
Stefan Thomas
27645c234a [CHORE] Currency: JavaScript has Math.exp for e^x, so we should use it. 2014-05-11 01:54:15 -07:00
Nicholas Dudfield
5280d994a2 Fix *U*Int64 parsing, add hardcore mode to ledger verifier. 2014-05-06 14:54:22 +07:00
Nicholas Dudfield
12f43a5334 Remove all traces of (now) unused tag_segment 2014-05-06 14:16:53 +07:00
Nicholas Dudfield
4f0399180c Reinstate disabled test (Thanks to encoded reminder) 2014-05-06 13:56:20 +07:00
Nicholas Dudfield
ea11d34254 Less slicing and dicing of tag_segment/indexes 2014-05-06 13:47:37 +07:00
Nicholas Dudfield
a222f2be98 Updates to allow verify_ledger_json.js to calculate account_state hash 2014-05-06 13:34:01 +07:00
wltsmrz
a48a25e236 Optional account_tx binary parsing 2014-05-05 15:05:02 -07:00
Stefan Thomas
473d8a8d8c [CHORE] Bump version to 0.7.36 2014-05-02 14:06:53 -07:00
Stefan Thomas
41ea820ae0 [FEATURE] Transaction: Allow canonical signing to be disabled via config. 2014-05-02 14:06:53 -07:00
wltsmrz
0558ad689a Async transaction sign 2014-05-02 12:45:26 -07:00
wltsmrz
3199aa438a Allow remote signing - broken options 2014-05-02 12:41:52 -07:00
Stefan Thomas
c3f630c27f Merge pull request #72 from emschwartz/message-signing
[FEATURE] New Message class for sigs on arbitrary data
2014-05-02 10:59:25 -07:00
Evan Schwartz
cf3a21a712 [CHORE] Merged PubKeyValidator into Account class 2014-05-01 20:28:55 -07:00
Evan Schwartz
d8504a3001 [CHORE] Changed variable name to make Stefan happier 2014-05-01 19:37:59 -07:00
Evan Schwartz
a2b07d5edd [FIX] Handling public key validation for unfunded accounts 2014-05-01 17:22:20 -07:00
Evan Schwartz
13a6a2c335 [CHORE] Added pre-built sjcl with additional functions included 2014-05-01 16:29:23 -07:00
Evan Schwartz
e19be192bd [FIX] Point coordinates should be converted to psuedo mersenne primes 2014-05-01 13:14:55 -07:00
Evan Schwartz
c32216c9e5 [CHORE] Added account param to signing functions 2014-05-01 12:08:14 -07:00
Evan Schwartz
904082a86c [FEATURE] New Message class for sigs on arbitrary data
This includes supporting files that can sign arbitrary data
with a signature that enables public key recovery. It also
includes the PublicKeyValidator class that can verify whether
a given public key is active for an account by looking in its
AccountRoot.
2014-04-30 18:41:18 -07:00
Evan Schwartz
f56a20d697 [FIX] Replaced Account.is_valid() with Account.isValid() 2014-04-30 18:41:18 -07:00
Evan Schwartz
8275e036c9 [CHORE] Modified functions not to overwrite entire prototype 2014-04-30 18:38:36 -07:00
wltsmrz
903e480130 Fix for missing transaction.remote 2014-04-25 01:38:01 -07:00
wltsmrz
30fd0e7bff Finalize before setting final transaction state 2014-04-25 00:08:26 -07:00
Stefan Thomas
fbdef6eea0 [BUG] UInt#parse_number should support zero. Add tests. 2014-04-24 09:01:18 -07:00
wltsmrz
5a04ce9629 Use binary sequence increment 2014-04-23 14:42:29 -07:00
wltsmrz
693e2aaae7 Decrement transaction sequence if transaction.complete fails 2014-04-23 14:39:30 -07:00
wltsmrz
43deeaf5fb Remove logging 2014-04-23 14:20:41 -07:00
wltsmrz
cbba7727f2 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-04-23 14:19:19 -07:00
wltsmrz
52e1665e72 Fixes for per-transaction defined secret and offline errors 2014-04-23 14:19:02 -07:00
sublimator
66ea770287 Fix README
1000th
2014-04-23 18:23:25 +07:00
wltsmrz
18efa5d742 Emit an error on invalid secret, cleanup 2014-04-23 03:56:36 -07:00
wltsmrz
802212bbdc Merge pull request #71 from emschwartz/develop
[FEATURE] Added setRegularKey transaction and more accountSet flags
2014-04-22 19:06:42 -07:00
Evan Schwartz
7f59fb917c [FEATURE] Added setRegularKey transaction and more accountSet flags 2014-04-22 14:57:13 -07:00
wltsmrz
14f409ff56 Properly convert JS time to Ripple time in OfferCreate transactions 2014-04-18 23:08:19 -07:00
wltsmrz
8ffd0b13a3 Cleanup 2014-04-17 15:19:08 -07:00
wltsmrz
969873441e Recognize account option as equivalent to source in transaction construction 2014-04-15 12:47:21 -07:00
wltsmrz
282ac6d8ab Fix transaction constructor 2014-04-15 12:38:57 -07:00
wltsmrz
1e3c96b14f Fix transaction finalize 2014-04-15 12:27:33 -07:00
wltsmrz
b14fab8aa7 Check remote exists in transaction.complete 2014-04-10 23:29:16 -07:00
Stefan Thomas
be33b1be60 [BUG] Don't set canonical flag when remote signing. 2014-04-10 08:16:03 -07:00
wltsmrz
06288e798e Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-03-25 17:23:31 -07:00
wltsmrz
0de7d84862 Use LRU cache API to prevent multiple transaction events for the same transaction 2014-03-25 17:23:28 -07:00
Stefan Thomas
58afce517a [DOCS] Add npm badge to README. 2014-03-24 04:47:37 +01:00
Stefan Thomas
87ba2abc9a [BUG] Undo previous commit making append_byte_array too loose.
This commit introduces an alternative way of setting the canonical signature
flag, without compromising the strictness of append_byte_array input
sanitizing.
2014-03-22 03:18:11 -07:00
Stefan Thomas
716fd0b938 [CHORE] Improved Amount#parse_quality w/ demurrage support, drops->XRP, etc.
Amount#parse_quality is made currency-aware. This allows it to adjust for XRP as
the base currency, as well as for interest-bearing or demurring base currencies.
2014-03-22 02:38:03 -07:00
Stefan Thomas
893fc4c168 [CHORE] Add Amount#invert mathematical utility function. 2014-03-22 00:47:41 -07:00
Stefan Thomas
6f5cf8506f [CHORE] Better variable names in Amount#parse_quality. 2014-03-21 23:56:13 -07:00
Stefan Thomas
c808cb0a1c [CHORE] Add ability to apply demurrage at the time of product/ratio calculation. 2014-03-21 18:43:22 -07:00
Stefan Thomas
5f677a86a7 [CHORE] Update SJCL. 2014-03-20 17:38:46 -07:00
Stefan Thomas
11540f8cd9 [CHORE] Allow integer strings for server "port" setting. 2014-03-20 17:38:46 -07:00
Stefan Thomas
9d6ccdcab1 [CHORE] Enable signature canonicalization. 2014-03-20 17:38:46 -07:00
wltsmrz
2267e599c0 Update HISTORY 2014-03-18 17:13:47 -07:00
wltsmrz
687bcc8539 Add HISTORY.md 2014-03-18 16:35:01 -07:00
wltsmrz
e64dba839c Bump version 2014-03-18 16:07:45 -07:00
wltsmrz
a651b6154d Properly choose ledger identifier in requestTransactionEntry 2014-03-18 12:00:54 -07:00
wltsmrz
4b5e75a8ad Add initial submit index and last ledger sequence to transaction summary 2014-03-18 11:26:00 -07:00
wltsmrz
bdd24bada9 Use binary account_tx on remote reconnect 2014-03-17 13:33:06 -07:00
wltsmrz
6e4a9179c1 Generate transaction hash in account_tx automatic binary handling 2014-03-17 13:21:54 -07:00
wltsmrz
b0c38ff566 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-03-15 22:02:42 -07:00
wltsmrz
e97a3966c1 Automatically parse binary account_tx response 2014-03-15 22:02:31 -07:00
Nicholas Dudfield
d0aa86bf97 Updated bundled sjcl.js to include typo fix from 007c2e7e5c 2014-03-15 14:45:23 +07:00
wltsmrz
b17eb8ed0d Check missing secret first in tx.complete 2014-03-13 11:34:07 -07:00
wltsmrz
7dcfa0a232 Set tx.finalized before changing state to validated/failed 2014-03-13 11:32:20 -07:00
wltsmrz
05c466bebe Add switch break 2014-03-11 16:36:53 -07:00
wltsmrz
0f7c80d76a Resubmit transactions failed with telINSUF_FEE_P 2014-03-11 16:35:48 -07:00
wltsmrz
99599ba673 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-03-10 16:29:08 -07:00
wltsmrz
85f75b4543 Emit tejSecretUnknown if secret is missing during signing, enhancements for ripple-rest 2014-03-10 16:28:41 -07:00
Stefan Thomas
37a22186ca Add memo field binary types. 2014-03-10 03:37:13 -07:00
sublimator
007c2e7e5c Fix typo 2014-03-08 23:37:25 +07:00
wltsmrz
a7581b1ec8 Whitelist build/sjcl 2014-03-07 14:52:25 -08:00
wltsmrz
06c662cc14 Add build/sjcl, remove grunt postinstall step 2014-03-07 14:45:38 -08:00
wltsmrz
7feafaa320 Add build, test, Gruntfile, Makefile to npm files 2014-03-07 13:53:12 -08:00
wltsmrz
1c06baf5db Add grunt postinstall script 2014-03-07 13:31:44 -08:00
wltsmrz
a188ae6ace Cleanup 2014-03-07 13:31:37 -08:00
wltsmrz
c0db5e251a Add transaction.lastLedger, whitelist type_hex path property 2014-03-07 11:55:46 -08:00
wltsmrz
bc427204c6 Cleanup 2014-03-07 11:54:02 -08:00
wltsmrz
976de00242 Update remote init test 2014-03-03 15:27:38 -08:00
wltsmrz
a098b0cf02 Fix trace validation 2014-03-03 15:08:38 -08:00
wltsmrz
70d28fc15e Fix remote storage validation 2014-03-03 13:20:47 -08:00
wltsmrz
815eed427f Validate remote configuration. Fixes #58 2014-03-03 13:10:56 -08:00
wltsmrz
55e74671a7 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-03-03 12:09:16 -08:00
wltsmrz
e595291c95 Merge pull request #62 from sublimator/develop
Set VER_ACCOUNT_ID on address returned by KeyPair.get_address
2014-03-03 12:09:10 -08:00
wltsmrz
47db68ff45 Use lru-cache API 2014-03-03 11:55:57 -08:00
Nicholas Dudfield
e227a541e7 Set VER_ACCOUNT_ID on address returned by keypair
Just a decent default, client code can still set_version before base58 encoding.
2014-03-03 11:09:15 +07:00
wltsmrz
7a88165e16 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-02-28 16:27:24 -08:00
wltsmrz
5ed148af75 Persistent transactions interface (Gateway REST API) 2014-02-28 16:27:09 -08:00
Stefan Thomas
1329de5344 Log: Cleanup some unused code. 2014-02-27 23:39:28 -08:00
Stefan Thomas
a003d261ea Log: New logging system.
Right now, all I've done is move the logging function from utils to its own
file. I've also refactored it and created some classes.

Next step would be to somehow get rid of the trace setting. The Remote class
should have nothing to do with logging settings. Perhaps we can keep the setting
for backwards compatibility only, but the main way to turn logging on/off or
filter logging messages should be through the Log class.
2014-02-27 23:38:45 -08:00
wltsmrz
37065123e5 Catch max fee exceeded on fee adjust 2014-02-27 15:13:15 -08:00
wltsmrz
44dd0ca4a3 Merge pull request #60 from sublimator/develop
Proposed fix for #51 and #57
2014-02-27 12:14:16 -08:00
wltsmrz
15304237d1 Don't automatically resubmit tefMAX_LEDGER, maintain transaction state, add transaction.iff(fn, callback) to be executed on each submission 2014-02-26 17:31:59 -08:00
Nicholas Dudfield
acfc1bbb8c Proposed fix for #51 and #57 2014-02-26 13:57:48 +07:00
wltsmrz
75a732e0ad Bump submitIndex on resubmit 2014-02-24 13:43:20 -08:00
wltsmrz
a46bff3c5e Bump version 2014-02-20 15:49:13 -08:00
wltsmrz
8fcb694f1d Fix account requests with object argument 2014-02-20 15:48:12 -08:00
wltsmrz
ef758b17b1 Bump LRU cache max size to 100 2014-02-20 14:23:17 -08:00
wltsmrz
b9646c51b8 Automatically resubmit on tefMAX_LEDGER 2014-02-19 16:08:15 -08:00
wltsmrz
e2f59ce975 Bump ripple-lib version 2014-02-19 14:41:28 -08:00
wltsmrz
c3ceba1f05 Cleanup 2014-02-19 14:06:55 -08:00
wltsmrz
573b38cc19 Add lru-cache dependency; make remote._received_tx an lru-cache with specified max length 2014-02-19 13:00:38 -08:00
wltsmrz
5ca5c73c34 Clear caches when queue empties 2014-02-19 12:21:55 -08:00
wltsmrz
5a15c5b1d5 Set LastLedgerSequence to current_ledger_index + 8 on outgoing transactions 2014-02-19 11:10:05 -08:00
wltsmrz
c60097f8c5 Change optional ping interval units to seconds 2014-02-18 16:41:24 -08:00
wltsmrz
7f13a71252 Use account_tx outbound filter, only query account_tx if the pending queue is non-empty 2014-02-18 16:33:31 -08:00
sublimator
5c8550b364 Update serializedtypes-test.js 2014-02-15 09:31:59 +07:00
wltsmrz
f27be38ca9 Add automatic ping option 2014-02-10 13:25:20 -08:00
Stefan Thomas
aed6b7754e Amount: Support passing demurrage currencies to Amount#parse_human.
If a reference date is provided as an option, the method will apply the
demurrage/interest rate compounded to that date.
2014-02-09 23:07:04 -08:00
Stefan Thomas
0772ffb6ed Currency: Behavior change for to_json for demurrage currencies.
Currency#to_json should output a format that can be successfully converted back
to a Currency object via from_json. So for demurrage currencies it should output
the full hex currency code.

Currency#to_human on the other hand should always print something a human will
understand. For demurrage currencies we'll print the three-letter code for now.
2014-02-09 23:07:04 -08:00
Vahe Hovhannisyan
37e6d95cbc Index: Add UInt256, change UInt160 and Seed paths. 2014-02-07 15:49:09 -08:00
Vahe Hovhannisyan
644b611b9b Transaction: Comment fix. 2014-02-07 14:21:59 -08:00
sublimator
b21be326fe SLE TODO for binformat 2014-02-05 23:15:00 +07:00
Stefan Thomas
3d9cea62ff Add new fields to binformat. 2014-02-04 22:21:43 -08:00
Stefan Thomas
a15da9ade1 Remove redundant information in binformat.js. 2014-02-04 21:38:25 -08:00
Stefan Thomas
a07b76a28c Move field type maps to binformat.js. 2014-02-04 21:38:20 -08:00
Stefan Thomas
372c508911 Improve error message for unknown field 2014-02-04 15:40:50 -08:00
Stefan Thomas
257e9da563 Fix reference to Transaction#parseJson. 2014-02-04 15:40:10 -08:00
Stefan Thomas
cdfb7989b0 Better error message for unknown fields. 2014-02-03 18:11:04 -08:00
Nicholas Dudfield
b01c15847c Fix binary serialization of Vector256 2014-02-01 11:02:10 +07:00
Nicholas Dudfield
23528293e0 Fix binary parsing of Vector256 2014-02-01 10:46:04 +07:00
wltsmrz
430dfef23d Bump ripple-lib version 2014-01-28 16:32:14 -08:00
wltsmrz
215a3f1669 Interface for storing external pending transaction queue 2014-01-28 15:03:16 -08:00
Stefan Thomas
f678f47155 Amount: Full demurrage support. 2014-01-25 11:31:56 -08:00
Stefan Thomas
fa07601a2a UInt: Add UInt#_update for creating subclasses that have dependent state. 2014-01-25 11:30:58 -08:00
Stefan Thomas
0d4357232c Fix grunt watch. Enable caching, only compile debug version. 2014-01-25 11:25:21 -08:00
Stefan Thomas
014514a4da Add a utility function for converting back from JS time to Ripple epoch. 2014-01-25 00:18:57 -08:00
Stefan Thomas
86c35d7d9c Add a new simple test for XRP IOUs in PathSet. 2014-01-24 05:25:30 -08:00
Stefan Thomas
9f76907f51 Currency: Add support for complex currencies. (UInt160)
This patch might regress the performance of the Currency class and by extension
the Amount class. Since Amount is on a lot of hot paths in the client we should
make sure this isn't a major problem.

As for compatibility, this patch is a major change, but it should maintain the
public interface very well, which the exception of some strange edge cases (e.g.
Currency.from_json(1337)), which weren't well-defined before anyway. Any code
that accesses _value directly (shame on you!) will need to be fixed. There
aren't any such references in ripple-client or the rippled test suite, so I
think we're looking pretty good.
2014-01-24 05:24:46 -08:00
sublimator
4e67167394 Fix usage in decode_binary.js 2014-01-22 12:49:36 +07:00
wltsmrz
292b6825fc Merge pull request #48 from miracle2k/signing_hash
Fix signingHash calls; make rsign output pre-sign hash.
2014-01-21 16:54:06 -08:00
wltsmrz
aed87f7437 Merge pull request #47 from miracle2k/decode_script
Add utility script to decode binary blobs.
2014-01-21 16:53:58 -08:00
Michael Elsdörfer
c95d976e84 Fix signingHash calls; make rsign output pre-sign hash. 2014-01-19 16:04:38 +01:00
Michael Elsdörfer
7bbab0759a Add utility script to decode binary blobs. 2014-01-19 16:01:14 +01:00
sublimator
2396a53b03 Make order book subscription work 2014-01-19 15:58:23 +07:00
wltsmrz
43ee82af57 Remove extraneous timing 2014-01-13 15:42:55 -08:00
wltsmrz
3308e0ea92 Fix merge conflict 2014-01-13 15:41:20 -08:00
wltsmrz
61a6db1641 Cleanup transactionqueue 2014-01-13 15:38:40 -08:00
wltsmrz
43eb4c3bfe Prevent duplicate 'transaction' events from Remote 2014-01-13 11:59:27 -08:00
wltsmrz
8538b3ccf2 Merge pull request #43 from sublimator/develop
Disable RTS for local signing
2014-01-13 11:27:27 -08:00
Nicholas Dudfield
f9bb7094e9 Disable transaction resubmission when remote signing. Throw error when attempt to build_path when using local_signing 2014-01-09 13:48:03 +07:00
wltsmrz
54b7099d01 Fix orderbook subscribe 2014-01-08 15:47:33 -08:00
wltsmrz
4ce04a5c90 requestTransactionEntry arguments 2014-01-08 15:13:31 -08:00
wltsmrz
19e29722dc Fix orderbook unsubscribe 2014-01-08 15:13:18 -08:00
wltsmrz
99351aa2dc Add Transaction.transactionManager getter for convenience 2014-01-07 10:28:55 -08:00
wltsmrz
ef6aca8d12 Don't store complete transactions in TransactionManager sequence cache 2014-01-07 10:18:33 -08:00
wltsmrz
b44f22c87f Emit 'signed' event when transaction is resigned 2014-01-07 10:17:58 -08:00
wltsmrz
ca653c42f1 Update license 2014-01-07 03:14:07 -08:00
wltsmrz
5544752dcd Update license 2014-01-07 03:12:06 -08:00
wltsmrz
4082bd2a0a Fix ledger index argument to transactionEntry, add flexibility to remote.transaction 2014-01-07 01:34:04 -08:00
wltsmrz
626164a8ab Fix requestTransactionEntry arguments, add flexibility to remote.transaction 2014-01-07 01:23:54 -08:00
wltsmrz
848c203b81 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-01-06 09:42:57 -08:00
wltsmrz
9f92a8dcce Typo. Fixes #39 2014-01-06 09:40:52 -08:00
Stefan Thomas
c8bb6e2a6a Fix last commit. 2014-01-05 14:41:11 -08:00
Stefan Thomas
f135021c52 Fix endless loop when creating an Account object for a non-existent account. 2014-01-05 14:09:20 -08:00
wltsmrz
f7dc3b9fa1 Merge pull request #38 from sublimator/develop
Add `SerializedObject.check_no_missing_fields`, fixing regression in checking for `binformat.REQUIRED` fields
2014-01-04 21:22:38 -08:00
Nicholas Dudfield
967317f37e Add SerializedObject.check_no_missing_fields 2014-01-05 11:36:35 +07:00
wltsmrz
b5d29533ee Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2014-01-03 20:13:35 -08:00
wltsmrz
a5c1dd1089 Use server.computeFee 2014-01-03 20:13:04 -08:00
wltsmrz
fd614ce0df Separate Server fee calculation, select fee-optimal servers while submitting a transaction 2014-01-03 20:08:24 -08:00
Stefan Thomas
eaf01312e4 More general secret auto-fill and ability to override with Transaction#secret. 2014-01-02 18:52:57 -08:00
wltsmrz
5c3f3ff0f1 server_status rippled event doesn't exist 2013-12-31 14:36:15 -08:00
wltsmrz
4a2515a6b2 Update license 2013-12-31 14:36:04 -08:00
wltsmrz
c3a8d37e1c Refactor 2013-12-31 12:31:02 -08:00
wltsmrz
66af0a0b8e Object logging 2013-12-31 11:31:34 -08:00
wltsmrz
1a093c165e Cleanup 2013-12-30 17:48:33 -08:00
wltsmrz
7182c85f11 API convert additional classes 2013-12-30 15:26:06 -08:00
wltsmrz
eed4a932bd Update bin/validate_address 2013-12-30 15:17:52 -08:00
wltsmrz
b5f4fdf918 Remove validate_account (it exists as bin/validate_address.js) 2013-12-30 15:14:53 -08:00
wltsmrz
ce9e2c9539 Allow accounts_proposed stream, check transaction.validated before finalizing transactions 2013-12-30 15:12:15 -08:00
wltsmrz
1cf0fbbde4 Add accounts_proposed setters, default rtAccounts to accounts_proposed 2013-12-30 15:11:12 -08:00
wltsmrz
10d5725919 Fix merge conflicts 2013-12-30 13:28:15 -08:00
wltsmrz
e9ec3ec3ef Merge pull request #36 from sublimator/develop
Fix bug in (redundant) check for transaction result immediately before resubmission
2013-12-28 22:07:54 -08:00
Nicholas Dudfield
95c7acb210 Fix bug in (redundant) check for transaction result immediately before resubmission 2013-12-29 11:55:54 +07:00
Stefan Thomas
65b035267c Remove comment that doesn't make sense in the new context. 2013-12-27 16:55:02 -08:00
Vahe Hovhannisyan
f10bc6718c Account.prototype.line: add a check. 2013-12-27 14:31:49 -08:00
Vahe Hovhannisyan
5229a3d507 Add Account.prototype.line. Retrieve this account's single trust line. 2013-12-27 11:57:29 -08:00
wltsmrz
e7b6050b82 Add bin/validate_address 2013-12-24 17:19:25 -08:00
Stefan Thomas
38a6e8b009 Fixing OrderBook#_subscribe (WIP). 2013-12-24 14:57:39 -08:00
Stefan Thomas
96b46d2394 Added Request#addBook. 2013-12-24 14:57:06 -08:00
wltsmrz
d401a70a2a Logging objects in browser 2013-12-24 13:20:12 -08:00
wltsmrz
9ad5337e7b Cleanup 2013-12-24 13:19:58 -08:00
wltsmrz
03c7b6b2aa Validate ledgerClosed messages and reject past ledgers 2013-12-23 18:06:36 -08:00
wltsmrz
94e5c3ddf1 Use constant Ripple-time offset 2013-12-23 14:08:52 -08:00
wltsmrz
caac293be5 Server logging 2013-12-23 11:53:52 -08:00
wltsmrz
faae634853 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-12-23 11:49:30 -08:00
wltsmrz
627acdbfde Update in-browser logging to accommodate n-args 2013-12-23 11:48:39 -08:00
Stefan Thomas
a7532b5f55 Disable ripple-lib in Safari iOS < 5 and Safari Mac < 6.
Actively disabling support for these browsers allows us to catch and report the
problem rather than trying to connect and failing for unknown reasons.
2013-12-23 10:35:28 -08:00
Stefan Thomas
9596787cad Throw specific exception when there is no websocket support detected. 2013-12-23 10:31:50 -08:00
wltsmrz
6cdeacdb90 Remote: Only log set_state when the state will actually change. Only set state online when connection_count === 1 2013-12-19 17:46:57 -08:00
wltsmrz
1b6945f74d Prevent NoOp transaction recycling 2013-12-19 17:45:20 -08:00
wltsmrz
675a599876 Log server URL for enhanced debugging 2013-12-17 13:22:49 -08:00
wltsmrz
94c57bc0d8 Cleanup 2013-12-17 12:56:53 -08:00
wltsmrz
667919cea1 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-12-17 12:36:05 -08:00
wltsmrz
9870761e32 Pass arbitrary number of arguments to utils.logObject 2013-12-17 12:34:41 -08:00
wltsmrz
8ef6fdea14 Merge pull request #35 from sublimator/develop
Keep track of all transactionIDs for a given Transaction that go on the network
2013-12-17 12:26:38 -08:00
wltsmrz
5c911367b7 Merge pull request #34 from chgwei/develop
Improvement `remote.request_book_offers` parameters passing
2013-12-16 20:20:44 -08:00
Nicholas Dudfield
e34cf6ebcf Remove unused methods from TransactionQueue 2013-12-15 10:09:54 +07:00
Nicholas Dudfield
620a33b7bd Keep track of all transactionIDs for a given Transaction that go on the network 2013-12-15 10:01:29 +07:00
Cheng wei
e65bec78a1 Improvement remote.request_book_offers parameters passing
As the example  in doc reference:
var request = remote.request_book_offers({
gets: {
'currency':'XRP'
},
pays: {
'currency':'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
});
It will raise `TypeError: Cannot read property 'currency' of
undefined`. Fixed issue with parsing parameters
2013-12-12 02:30:24 +08:00
Stefan Thomas
d33c8e46af Finalized transactions should seize all activity. 2013-12-09 18:55:53 -08:00
Stefan Thomas
472a5091ae Add grunt build step to npm test. Should fix Travis. 2013-12-09 18:44:40 -08:00
Vahe Hovhannisyan
ff5e9fcaa9 Transaction: semicolon, comma fixes. 2013-12-09 12:36:14 -08:00
wltsmrz
4a027bdcdf Add remote.disconnect callback 2013-12-05 17:10:04 -08:00
wltsmrz
dbdfc262b6 Only one 'submitted' event will be emitted per transaction submission request 2013-12-05 17:04:10 -08:00
wltsmrz
dc2b69d2c2 Remove a single space 2013-12-03 12:01:01 -08:00
wltsmrz
9a78d36b72 Add grunt build documentation. Fixes #31 2013-12-03 11:59:10 -08:00
wltsmrz
d14346ba15 Disable server activity check 2013-11-27 18:24:25 -08:00
wltsmrz
992b4c53b8 WebSocket isn't a Node-style EventEmitter in the browser 2013-11-27 17:29:25 -08:00
wltsmrz
385113c2f5 Remove logging 2013-11-27 15:42:53 -08:00
wltsmrz
dc04bbe737 Enhanced security for idle server reconnect 2013-11-27 15:42:05 -08:00
wltsmrz
b6a66e1820 Update readme. Fixes #15 2013-11-27 14:32:13 -08:00
wltsmrz
bcceceb2e0 In case there happens to already be a tx_json, don't overwrite it 2013-11-26 12:43:34 -08:00
wltsmrz
19c0585ff0 Remove extraneous stuff 2013-11-26 12:39:14 -08:00
wltsmrz
97df7472f5 Provisionally disable transaction broadcasting 2013-11-26 12:32:53 -08:00
wltsmrz
f05577d7df All transaction result objects will have tx_json property 2013-11-25 11:52:28 -08:00
wltsmrz
4d94aef80c Add transaction.invoiceID setter 2013-11-22 12:43:31 -08:00
wltsmrz
0902640fc0 Update transaction.jS 2013-11-21 13:19:05 -08:00
wltsmrz
bcd5e38976 Fix/refactor account_root request 2013-11-20 12:32:03 -08:00
wltsmrz
dfedc86fb7 API update 2013-11-19 14:47:57 -08:00
wltsmrz
78d110c8d1 Update transactionmanager 2013-11-19 14:39:44 -08:00
wltsmrz
4e6ae229c0 Avoid circular JSON stringification during transactionmanager trace 2013-11-18 14:52:16 -08:00
wltsmrz
49cd062cb7 Return self in set_server for chaining 2013-11-18 13:22:56 -08:00
wltsmrz
1fa196037e Fix direct requirements for tests 2013-11-18 13:08:05 -08:00
wltsmrz
674ce90eaf Don't begin to check server activity until connected 2013-11-18 13:04:11 -08:00
wltsmrz
a306407588 Cleanup 2013-11-15 23:30:18 -08:00
wltsmrz
5c81441634 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-15 23:15:04 -08:00
wltsmrz
cff9902802 API conversion 2013-11-15 23:13:49 -08:00
wltsmrz
08911ec2ee Refactor, begin API conversion 2013-11-15 23:13:34 -08:00
wltsmrz
79b698f232 Cleanup 2013-11-15 23:12:35 -08:00
wltsmrz
5253278c29 Normalize transactions to acount transaction stream, cleanup 2013-11-15 23:12:28 -08:00
wltsmrz
48aa5b6c01 Add server activity check / reconnect defunct servers 2013-11-15 22:38:48 -08:00
wltsmrz
7e5c4af53d Cleanup, comments, update for new style 2013-11-14 14:30:29 -08:00
wltsmrz
9b3bb77d0e Merge pull request #27 from stevenzeiler/develop
[TEST] Add chai and sinon for testing, begin testing remote.js
2013-11-13 18:35:17 -08:00
wltsmrz
a72995642c request_connect > requestConnect 2013-11-13 17:20:04 -08:00
wltsmrz
12562d68f8 Add camelcase API, remote.request accepts a string command argument 2013-11-13 17:11:37 -08:00
wltsmrz
8805610413 Create account transactionmanagers in account constructor 2013-11-13 16:12:04 -08:00
wltsmrz
b9082a425f Normalize objects emitted on transaction success 2013-11-13 11:49:18 -08:00
wltsmrz
c1f5705ef8 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-13 11:41:17 -08:00
wltsmrz
69758cd631 Add transactionmanager debugging 2013-11-13 11:41:13 -08:00
Stefan Thomas
05f3a97042 UInt160 can be an account or a plain hash.
The UInt160 class used to be hardcoded to be an Account. This commit changes it
so it can be used as an account or a plain hash. It will try to automatically
self-classify based on how it is initialized.

In the future we may want to have some dedicated classes rather than a
single configurable UInt160.
2013-11-12 15:51:50 -08:00
Steven Zeiler
1db2187e79 [TEST] Add chai and sinon for testing.
Begin testing remote.js
    Add initialization of 'note variable' and a comment that it should be removed
2013-11-12 14:13:15 -08:00
Stefan Thomas
ae68e3a1a6 Change "success" event parameters to more closely match "proposed" and "error". 2013-11-11 13:29:02 -08:00
Stefan Thomas
96ed994932 Fixes on XRP path serialization/deserialization. 2013-11-11 12:17:09 -08:00
Stefan Thomas
b2580ec178 Disambiguate PathSets with XRP vs XRP IOUs.
XRP IOUs are no longer valid, however they do exist in the network's historical
transactions, so the serialization and deserialization need to be able to handle
them.
2013-11-11 11:49:52 -08:00
Stefan Thomas
e065238758 Fix transaction signature cache.
The Transaction#sign method would notice that a previous signature was still
valid and skip signing again. Great, except it would throw the old
signature away first, leaving no signature at all. Fixed.
2013-11-11 05:57:40 -08:00
Stefan Thomas
34ea528ade Add serialization of XRP as an IOU if explicitly asked for.
Unfortunately, there are some transactions in the history that use this format,
so we need to support it in order to be able to verify historic ledgers.
2013-11-08 16:36:37 -08:00
Stefan Thomas
1355dc135f Fix recursive SHAMap collision handling. 2013-11-08 15:55:20 -08:00
Stefan Thomas
9652a99589 Set same criteria for currency code validity in serializedtypes.js as currency.js. 2013-11-08 15:21:04 -08:00
Stefan Thomas
8dfdced942 Fix SHAMap node collision detection. 2013-11-08 15:00:45 -08:00
wltsmrz
e779f98fb8 Export ripple-lib/Request 2013-11-08 14:40:49 -08:00
Stefan Thomas
f633beafbf Update upstream. 2013-11-08 14:38:00 -08:00
wltsmrz
81d380fb90 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-08 14:26:59 -08:00
wltsmrz
4be5468485 Add account_currencies 2013-11-08 14:26:42 -08:00
Stefan Thomas
a8759f1390 Fix large 32-bit integers getting deserialized as signed ints. 2013-11-08 14:21:27 -08:00
wltsmrz
5b1b41ae80 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-08 14:03:09 -08:00
wltsmrz
75ed909aeb Implement local transactionID generation 2013-11-08 13:58:30 -08:00
Stefan Thomas
069852a501 Fix parsing Hash256s that start with FF. 2013-11-08 12:49:13 -08:00
Stefan Thomas
5def7ba917 Add SHAMaps, metadata serialization and transaction hash calculation. 2013-11-07 22:36:06 -08:00
Stefan Thomas
74ef8f8400 Fix Int64 parsing. 2013-11-07 21:56:26 -08:00
wltsmrz
0e5431468c Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-07 14:05:40 -08:00
Stefan Thomas
e65f975e29 Transaction#hash. 2013-11-07 13:56:07 -08:00
wltsmrz
0f80f6d4ae Extend rippleerror properties 2013-11-07 11:47:10 -08:00
wltsmrz
3491fec469 Bump ripple-lib, mocha version 2013-11-06 01:13:02 -08:00
wltsmrz
4df88b6df5 Handle remote reconnects after max ledger wait, refactor 2013-11-06 00:41:56 -08:00
wltsmrz
2a763f8f03 Add account_currencies command 2013-11-05 17:06:51 -08:00
wltsmrz
a306d0d0e1 Do not overwrite accounts array on prepare_subscribe 2013-11-04 17:38:42 -08:00
wltsmrz
2e39f6d4a9 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-11-04 17:35:23 -08:00
wltsmrz
03930ecc9b Do not overwrite accounts array on prepare_subscribe 2013-11-04 17:30:05 -08:00
Justin Lynn
c3215e6387 add .travis.yml to silence e-mail notices 2013-11-04 17:26:50 -08:00
wltsmrz
31340c8bc1 Add Request.add_account 2013-11-04 17:26:22 -08:00
wltsmrz
fd07103e9a Request.accounts will append rather than overwrite 2013-11-04 17:00:32 -08:00
Vahe Hovhannisyan
43319267ad Add all available flags to Remote.flags. 2013-11-04 16:55:42 -08:00
Stefan Thomas
37da90e81d Typo. 2013-10-30 22:08:42 -07:00
wltsmrz
58bc1b1682 Add Request.broadcast. Subscribe to account transaction stream on all connected servers 2013-10-30 14:09:55 -07:00
wltsmrz
60e2aa613a Merge pull request #23 from tradespoke/patch-1
Update README.md
2013-10-29 23:54:35 -07:00
Filip Andersson
3f3b8dbfb9 Update README.md 2013-10-30 06:50:59 +00:00
wltsmrz
c5390100f5 Allow connection_offset of 0 2013-10-28 12:10:17 -07:00
wltsmrz
6f8d33005a Merge pull request #21 from sublimator/develop
Add hooks for logging web socket messages
2013-10-28 12:07:19 -07:00
sublimator
1c5b6b365a Add hooks for logging web socket messages
This can be used to capture web socket messages, interspersing them with metadata about the source of such messages. The rippled test suite could be captured (as per http://ndudfield.com/zencoding/rippled-capture) and it could also be useful for logging ripple-client messages for display.

The event names are pretty explicit about the intended use cases.
2013-10-25 14:42:55 +07:00
wltsmrz
8447d2c22d Bump subversion 2013-10-24 14:59:36 -07:00
wltsmrz
04b8bf277c Catch all error messages into rippleerror class 2013-10-24 12:30:27 -07:00
wltsmrz
fb3e15a079 Decrease default fee_cushion 2013-10-24 10:53:46 -07:00
wltsmrz
8959d9167f Always set build_path with local signing enabled. Fixes #20 2013-10-24 10:26:44 -07:00
wltsmrz
32d404bd44 Cleanup 2013-10-23 14:30:13 -07:00
wltsmrz
2415c668e4 Always resubmit on ter 2013-10-23 14:21:46 -07:00
wltsmrz
5c19ad2885 Pass any number of flags to set_flags 2013-10-21 16:30:46 -07:00
wltsmrz
73d41872cb Add TrustSet flags 2013-10-21 12:49:43 -07:00
wltsmrz
1eb2652edf Merge pull request #19 from moeadham/develop
[README] Correct typo
2013-10-17 20:47:20 -07:00
Moe Adham
997e561389 [README] Correct typo 2013-10-17 21:40:27 -04:00
wltsmrz
45fff5642d Resubmit after tefPAST_SEQ despite failed sequence query 2013-10-07 18:09:01 -07:00
wltsmrz
179dba81cc Bump version 2013-10-07 13:44:40 -07:00
wltsmrz
25f9d27206 More efficient to_human rounding 2013-10-06 19:19:58 -07:00
wltsmrz
fee2d3ad0e Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-10-06 03:35:46 -07:00
wltsmrz
6e54f34c4b Cache previous transaction signing hash, do not resign unless changed. Fixes #16 2013-10-06 03:34:34 -07:00
wltsmrz
7d631e5864 Round up XRP amounts. Fixes #17 2013-10-06 03:15:31 -07:00
wltsmrz
7ad0b0b093 Merge pull request #18 from mjethani/develop
Fixed issue with parsing of trade price.
2013-10-06 02:31:33 -07:00
wltsmrz
9571e7c130 More robust transactions. Load account_tx on remote reconnect 2013-10-06 02:28:11 -07:00
wltsmrz
b21d7aef0d Cleanup 2013-10-06 02:26:45 -07:00
wltsmrz
137a6a757e Cleanup 2013-10-05 15:28:30 -07:00
wltsmrz
12a5c3c701 Cleanup 2013-10-05 15:09:40 -07:00
wltsmrz
37b653eae6 Cleanup 2013-10-05 15:06:55 -07:00
wltsmrz
f24be618d8 Pause transaction processing and reload sequence on failed transactions 2013-10-05 03:23:59 -07:00
Manish Jethani
f077624212 Fixed issue with parsing of trade price.
The + operator has higher precedence, which causes the price to be read
as '' (empty string) no matter what the currency and issuer.

I believe this will fix the "Last price = n/a" error in the default
client as well.
2013-10-05 07:16:29 +05:30
wltsmrz
b4c120cea4 Fix #12 2013-10-02 21:29:52 -07:00
wltsmrz
5f69cad0cc Bump version 2013-10-02 13:29:08 -07:00
wltsmrz
76b5ca9a12 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-10-02 13:27:15 -07:00
wltsmrz
37234d2751 Fix bad signatures on resubmitted transactions 2013-10-02 13:23:02 -07:00
Vahe Hovhannisyan
abfab78f96 Docs: Add an example for request_book_offers 2013-09-28 07:56:27 -07:00
wltsmrz
53d704310a Bump version, include path to relocated jsbn for npm publishing 2013-09-26 17:56:55 -07:00
Vahe Hovhannisyan
ab1c409022 Fix stack trace bug on safari 2013-09-26 11:56:17 -07:00
wltsmrz
bf940fdec5 Do not log deprecation warnings by default 2013-09-25 18:35:36 -07:00
wltsmrz
6015ba7d25 Bump version 2013-09-24 13:04:44 -07:00
wltsmrz
72eb558f6a Bump dependencies version 2013-09-24 13:04:20 -07:00
wltsmrz
d74a7e9ea1 Update npmignore 2013-09-24 13:02:35 -07:00
Stefan Thomas
f259c7ebd7 Montgomery: Fix infinite loop for leading zero inputs. Add test. 2013-09-21 17:16:44 -07:00
Stefan Thomas
8d13065cf4 Added a benchmark for Montgomery exponentiation. 2013-09-21 16:49:34 -07:00
Stefan Thomas
5c36be59e5 More tests for Montgomery exponentiation. 2013-09-21 16:49:09 -07:00
Stefan Thomas
d2559dcdb8 Added Montgomery exponentiation for SJCL. 2013-09-21 15:23:55 -07:00
Stefan Thomas
6194d9bcd9 Left a console statement. Oops. 2013-09-21 05:50:28 -07:00
Stefan Thomas
64df821b38 JSBN and coverage tests cleanup.
Fixes compiler warning about SJCL.
Fixes coverage source highlighting issue.
Move JSBN outside of src/js/jsbn/.
2013-09-21 05:41:19 -07:00
Stefan Thomas
0986b37267 Added Jacobi functionality, more bn features - plus tests. 2013-09-19 22:24:49 -07:00
wltsmrz
26220239fa Bump version 2013-09-18 13:42:58 -07:00
wltsmrz
73fae67022 Update readme 2013-09-17 16:25:08 -07:00
wltsmrz
6dc15c6951 Update readme 2013-09-17 16:24:20 -07:00
wltsmrz
bc600a27b3 Add note about running tests 2013-09-17 16:23:03 -07:00
wltsmrz
c8e0ef01ac Bump dependencies versions 2013-09-17 15:32:07 -07:00
wltsmrz
db28f9ae46 Update npmignore 2013-09-17 15:29:27 -07:00
wltsmrz
7b4182b322 Revert "Update pathfind command arguments"
This reverts commit 0753d9cf4a.
2013-09-17 15:26:37 -07:00
wltsmrz
0753d9cf4a Update pathfind command arguments 2013-09-12 16:33:13 -07:00
wltsmrz
f337aa6a16 Use dot reporter for npm test 2013-09-12 16:24:25 -07:00
wltsmrz
7080611247 Use spec reporter for make test 2013-09-12 16:24:06 -07:00
wltsmrz
bab9fec836 Refactor currency parsing 2013-09-12 14:17:51 -07:00
wltsmrz
8dd1b62d78 Improve test coverage 2013-09-12 14:15:44 -07:00
wltsmrz
9eeb3faba3 Improve test coverage 2013-09-12 14:15:34 -07:00
wltsmrz
bba2e10e94 Test coverage 2013-09-11 14:22:47 -07:00
wltsmrz
943251b387 Refactor amount 2013-09-11 14:22:24 -07:00
wltsmrz
8b76db3942 Refactor amount 2013-09-11 13:36:06 -07:00
wltsmrz
2463fd9588 Fix human amount detection in .payment 2013-09-11 13:00:32 -07:00
wltsmrz
56a8ad3aa5 Fix base.js 2013-09-11 12:11:48 -07:00
Stefan Thomas
57aa1773cb Add the ability to generate addresses from keypairs. 2013-09-11 10:27:52 -07:00
Stefan Thomas
1f22456aed Ignore coverage related files. 2013-09-10 21:10:50 -07:00
wltsmrz
e784ad6d27 Fix grunt build with sjcl export 2013-09-10 17:46:56 -07:00
wltsmrz
068aea3ac4 Add new sjcl export for code coverage convenience 2013-09-10 17:15:52 -07:00
wltsmrz
40eccdb2fd Add new sjcl export for code coverage convenience 2013-09-10 17:13:55 -07:00
jatchili
3f2afdc39d Remove debugging statements 2013-09-10 16:49:25 -07:00
jatchili
bcaabd36be Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop
Conflicts:
	src/js/ripple/serializedtypes.js
	test/serializedtypes-test.js

JSONify complex structures before comparing them in tests.
2013-09-10 16:46:53 -07:00
jatchili
21aed214a7 messing around with serialized types test 2013-09-10 16:10:49 -07:00
wltsmrz
d761208878 Alias taker_gets and taker_pays 2013-09-10 16:00:19 -07:00
wltsmrz
2f7ce2841c transaction.payment will handle human amounts 2013-09-10 15:59:11 -07:00
wltsmrz
3fa3f6fb94 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-09-10 15:49:42 -07:00
wltsmrz
6f9c103d78 Update tests for future test coverage 2013-09-10 15:48:57 -07:00
Evan Schwartz
b131bd413c updated transaction options 2013-09-10 15:12:58 -07:00
wltsmrz
8e7d5d37b9 Remove extraneous file 2013-09-10 13:41:47 -07:00
wltsmrz
5f7a4fe042 Fix npm script running on windows 2013-09-10 12:36:28 -07:00
wltsmrz
24ef629da3 Specify parseInt base 2013-09-10 11:33:05 -07:00
wltsmrz
7e1e8a9503 Specify parseInt base 2013-09-10 11:26:41 -07:00
wltsmrz
3807c1ba6a Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-09-09 21:12:59 -07:00
wltsmrz
c3753ffc6a Allow options map for transaction commands. Closes #10 2013-09-09 21:12:45 -07:00
wltsmrz
41b66fc585 Allow options map for transaction commands. Closes #11 2013-09-09 21:11:15 -07:00
wltsmrz
95e547aff9 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-09-09 19:41:59 -07:00
wltsmrz
b6580dfe40 Cleanup 2013-09-09 15:26:21 -07:00
wltsmrz
6330777076 Cleanup 2013-09-09 14:59:19 -07:00
wltsmrz
2858579820 Remove colon 2013-09-09 14:49:14 -07:00
wltsmrz
2e7fcb0e76 Cleanup 2013-09-09 14:48:20 -07:00
wltsmrz
8cab1ae200 Cleanup 2013-09-09 14:42:07 -07:00
wltsmrz
dad760f9ba Cleanup 2013-09-09 14:28:15 -07:00
wltsmrz
e944f0f5c4 Cleanup 2013-09-09 13:58:43 -07:00
Evan Schwartz
379638da43 Merge branch 'newdocs' into develop
adding new docs to develop branch
2013-09-09 13:37:57 -07:00
Evan Schwartz
121bca2f1d about to merge back into develop branch 2013-09-09 13:37:09 -07:00
Evan Schwartz
7bf83e5c48 fixed link 2013-09-09 13:21:16 -07:00
Evan Schwartz
33c12ec93f added clickable links 2013-09-09 13:18:54 -07:00
Evan Schwartz
7a27bbb78c added listening to the network guide 2013-09-09 13:17:23 -07:00
wltsmrz
6ce83107c8 Cleanup 2013-09-09 13:05:40 -07:00
Evan Schwartz
41fb5e5b22 finished offer create guide 2013-09-09 12:06:37 -07:00
wltsmrz
8588e0c78f Fix account_lines 2013-09-09 11:59:40 -07:00
Evan Schwartz
2091d3ed29 indentation 2013-09-09 11:57:38 -07:00
Evan Schwartz
529aac8c37 added offer create guide 2013-09-09 11:57:03 -07:00
Evan Schwartz
428d31c4db added small link to guies 2013-09-09 11:07:52 -07:00
wltsmrz
aeba9ba05e Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-09-08 18:08:18 -07:00
wltsmrz
bf95285d90 Use assert.deepEqual, fix serializedtypes 2013-09-08 18:07:55 -07:00
wltsmrz
45292847ee Remove underscore devDependency 2013-09-08 18:07:30 -07:00
wltsmrz
aec3df1bf9 Remove comma 2013-09-08 17:43:19 -07:00
wltsmrz
8b1407613a Remove extraneous file 2013-09-08 17:38:02 -07:00
wltsmrz
2d68ce5f1b Update dependencies 2013-09-08 17:35:57 -07:00
wltsmrz
0a1d1f2ed4 Add Makefile 2013-09-08 17:35:50 -07:00
wltsmrz
25401bd08d Update ripple-lib tests to use mocha 2013-09-08 17:33:08 -07:00
Evan Schwartz
0ce98b126f small edit to the using remote guide 2013-09-06 17:24:38 -07:00
Evan Schwartz
db442f613e finished connecting guide 2013-09-06 17:21:16 -07:00
Evan Schwartz
b31d969d63 added connecting guide 2013-09-06 17:19:00 -07:00
Evan Schwartz
8a8159ee0b fixed bad link 2013-09-06 17:10:55 -07:00
Evan Schwartz
74c6852743 changed toc 2013-09-06 17:09:23 -07:00
wltsmrz
b9e29e8b6c Bump version 2013-09-06 17:06:49 -07:00
Evan Schwartz
9246449590 editing docs 2013-09-06 17:05:21 -07:00
Evan Schwartz
e3a6913cb0 edited readme 2013-09-06 15:47:04 -07:00
Evan Schwartz
6231d0102b changed format 2013-09-06 15:41:53 -07:00
wltsmrz
9630d92e0a Fix bin/rsign example sequence 2013-09-06 15:41:17 -07:00
Evan Schwartz
0b7ff197c8 added toc 2013-09-06 15:41:00 -07:00
Evan Schwartz
b55c547bb9 added links to readme and guides 2013-09-06 15:29:56 -07:00
Evan Schwartz
9b1c47278c fixed case 2013-09-06 15:26:59 -07:00
wltsmrz
aa6a9e9559 nextServer > next_server 2013-09-06 15:26:43 -07:00
Evan Schwartz
bddf4a8673 added links 2013-09-06 15:26:12 -07:00
wltsmrz
0aee56f4f1 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-09-06 15:23:09 -07:00
wltsmrz
fb94ef3cf3 Allow options object for complex remote commands 2013-09-06 15:22:42 -07:00
wltsmrz
7ff1e89824 Update account 2013-09-06 15:22:00 -07:00
Evan Schwartz
b5fcab50d1 added links 2013-09-06 15:21:54 -07:00
wltsmrz
69afa608bf Update transaction.js / orderbook.js 2013-09-06 15:17:42 -07:00
Evan Schwartz
9677b09ecc Merge branch 'develop' of github.com:emschwartz/ripple-lib into newdocs
just merging with remote
2013-09-06 15:16:28 -07:00
Evan Schwartz
1f3eb57fa4 added REFERENCE and GUIDES 2013-09-06 15:12:32 -07:00
wltsmrz
a501400caa Catch request errors 2013-09-06 14:27:07 -07:00
Stefan Thomas
69e44a66bb Changing to simplified version of new account_tx API. 2013-09-05 22:07:08 -07:00
wltsmrz
abec5386a6 Bump dependencies 2013-09-05 17:28:29 -07:00
jatchili
2e15bce98b Translate LedgerEntryType and TransactionResult into strings 2013-09-05 17:16:43 -07:00
wltsmrz
10ac0a5e42 Set message.result before emitting submitted event 2013-09-05 16:13:38 -07:00
wltsmrz
b723e031d1 Update rippleerror 2013-09-05 16:13:24 -07:00
wltsmrz
18c02cbb42 Add message.result = message.engine_result 2013-09-05 15:29:26 -07:00
wltsmrz
d89f04a622 Fix currency in path_rewrite 2013-09-05 15:20:17 -07:00
wltsmrz
ceea368a5c Proper max_fee comparison 2013-09-05 15:07:18 -07:00
wltsmrz
ef83019a4b Resubmit transactions on tooBusy 2013-09-05 13:17:32 -07:00
wltsmrz
28c90f1923 TransactionManager -- tec shouldn't decrement sequence 2013-09-04 17:03:19 -07:00
wltsmrz
8bc6a3cbcf Cleanup account_tx 2013-09-04 17:02:48 -07:00
wltsmrz
a46d08c6f4 Update readme 2013-09-04 17:02:30 -07:00
wltsmrz
7d63cb52cb Update readme 2013-09-04 14:40:40 -07:00
wltsmrz
81ff4eec2d Passive transaction validation -- add lost and missing events 2013-09-04 14:37:03 -07:00
wltsmrz
7a6d46acd3 Accommodate new account_tx 2013-09-04 14:34:37 -07:00
wltsmrz
700c6f0430 Update readme 2013-09-03 15:41:08 -07:00
wltsmrz
6688ad5d8d Update readme 2013-09-03 15:36:40 -07:00
wltsmrz
f3e1b6b39f Remote.ping uses new request.set_server 2013-09-03 15:29:40 -07:00
wltsmrz
d43bc13f48 request.set_server(string) selects by host 2013-09-03 15:28:32 -07:00
wltsmrz
a4ff3cbaac Update readme 2013-09-03 14:58:07 -07:00
wltsmrz
370fab5858 Update readme 2013-09-03 14:33:03 -07:00
wltsmrz
75d00f1778 Update readme 2013-09-03 14:31:03 -07:00
wltsmrz
d7ecbbf648 Update account 2013-09-03 14:13:21 -07:00
wltsmrz
bff8415ea5 Normalize RippleErrors 2013-09-03 13:57:58 -07:00
wltsmrz
0794f7b629 Update transaction queue 2013-09-03 13:52:26 -07:00
wltsmrz
b5a50aeba9 Add transaction abort 2013-09-03 13:48:59 -07:00
wltsmrz
f6cfcb6217 Rewrite rsign 2013-09-03 12:29:45 -07:00
wltsmrz
fd3a583abf Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-30 11:16:09 -07:00
wltsmrz
b551753fe4 Update readme 2013-08-30 11:12:47 -07:00
Vahe Hovhannisyan
b6283a554d Remote.book bug fix 2013-08-30 16:37:49 +04:00
wltsmrz
a65ba8f87d Add transaction-inbound, transaction-outbound events 2013-08-27 10:47:31 -07:00
wltsmrz
ffd23d34ab Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-26 10:43:48 -07:00
wltsmrz
75859a2c4d Update pending transaction fees 2013-08-26 10:43:13 -07:00
Stefan Thomas
166e35bf0e Disable currency validity check for now.
It's too strict unfortunately and not quick to fix.
2013-08-23 19:08:53 -07:00
Stefan Thomas
74da0c8a52 No need to turn the JS object into a string and back again. 2013-08-23 15:50:15 -07:00
Stefan Thomas
d5fb086b51 Digits appear in some currency codes in the ledger history.
We need to figure out what the exact allowed character set is - if there are any
restrictions.
2013-08-23 15:13:31 -07:00
Stefan Thomas
6fa2a220e7 Add some debug info to the currency parsing error. 2013-08-23 15:10:34 -07:00
wltsmrz
27fed3e737 Apply the scope of request to request callbacks 2013-08-22 12:06:13 -07:00
wltsmrz
13b62d72c6 Update readme 2013-08-22 11:53:43 -07:00
wltsmrz
4c6c967576 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-22 10:55:16 -07:00
wltsmrz
009143f724 Update remote 2013-08-22 10:55:09 -07:00
wltsmrz
c545e19e40 Include transaction message in inbound/outbound events 2013-08-21 17:19:17 -07:00
Stefan Thomas
87790b330e PathFind should pass on errors with the pathfind request. 2013-08-21 16:59:51 -07:00
Stefan Thomas
c9d081f2c6 Do not allow serialization of invalid accounts. 2013-08-21 16:58:49 -07:00
Stefan Thomas
222d49c4d8 Handle errors with initial subscribe request. 2013-08-21 16:58:37 -07:00
Stefan Thomas
ce8fd9ddbe Only subscribe to accounts if the Account object is set up correctly. 2013-08-21 16:58:09 -07:00
wltsmrz
ccd1758284 Add transaction-inbound and transaction-outbound events 2013-08-21 16:41:01 -07:00
Stefan Thomas
ba48078f9e Add tx_history command. 2013-08-21 11:20:12 -07:00
jatchili
f35df54eab Stringify input to BigInteger constructor 2013-08-20 18:46:11 -07:00
jatchili
f1334c6b92 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-20 17:36:24 -07:00
jatchili
7a5631a2ce Fix array and inner-object parsing 2013-08-20 17:36:12 -07:00
wltsmrz
9c9f8fae14 Update readme, validate all transaction addresses 2013-08-20 11:54:35 -07:00
wltsmrz
dc51b8ba48 Update readme 2013-08-17 16:25:08 -07:00
wltsmrz
e3edd5267d Fix secure configuration; Boolean constructor should be string 2013-08-16 13:15:16 -07:00
wltsmrz
8b69dfd154 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-15 11:53:47 -07:00
wltsmrz
8333c3fbfc Fix for typeof NaN === number 2013-08-15 11:53:38 -07:00
jatchili
083377651f Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-14 18:33:28 -07:00
jatchili
0c18f6157d SerializedObject to_json method, and a simple test for that. Tests are still preliminary, and refactoring is still necessary. 2013-08-14 18:33:01 -07:00
wltsmrz
66d71efa78 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-14 17:24:14 -07:00
wltsmrz
0811dec65c Update server 2013-08-14 17:21:08 -07:00
wltsmrz
b3822cc4c5 Update everything 2013-08-14 17:20:51 -07:00
Stefan Thomas
1305acb849 Bump version to 0.7.19. 2013-08-14 17:15:14 -07:00
Stefan Thomas
1e1e70d9a6 Add Amount#invert. 2013-08-14 17:11:30 -07:00
jatchili
942bfe88c1 passed tests (however, the test cases themselves are unverified.) 2013-08-12 18:44:34 -07:00
jatchili
63038d3603 basic tests for serializedtypes.js 2013-08-12 15:19:04 -07:00
wltsmrz
0f5fdbc772 Merge branch 'develop' of https://github.com/ripple/ripple-lib into robust-transactions 2013-08-12 10:40:07 -07:00
Stefan Thomas
8640176a07 Move debug statement in pathfind.js to proper place. 2013-08-09 17:10:25 -07:00
Stefan Thomas
e49838437e Add Account#lines. 2013-08-08 18:43:27 -07:00
Stefan Thomas
7c5e9bae2a Use the initial path find response as a first set of alternatives. 2013-08-08 18:43:27 -07:00
Vahe Hovhannisyan
08a2d771cd WebSocket support for some old browsers 2013-08-08 11:26:20 +02:00
wltsmrz
36f8ca1073 Merge branch 'robust-transactions' of https://github.com/ripple/ripple-lib into robust-transactions 2013-08-07 17:58:28 -07:00
wltsmrz
1e288c31af Merge pull request #9 from sublimator/robust-transactions
Allow hooking of the Server WebSocket constructor object
2013-08-07 17:47:27 -07:00
Nicholas Dudfield
e8144128d0 Naming style, oopz 2013-08-07 17:20:23 -07:00
Nicholas Dudfield
e5421effd5 Allow hooking of the Server WebSocket constructor object 2013-08-07 17:11:29 -07:00
wltsmrz
48a2bb9fe4 Update readme 2013-08-07 08:37:07 +09:00
wltsmrz
67d100796d Cleanup 2013-08-07 08:16:20 +09:00
wltsmrz
0f91bf0e98 Add custom RippleError 2013-08-07 07:35:37 +09:00
wltsmrz
1aaee7526b Cleanup 2013-08-07 06:26:43 +09:00
wltsmrz
fd0ce52cf6 Cleanup 2013-08-06 06:54:06 +09:00
wltsmrz
0fd973f58b Add ledger_hash paramter to transaction_entry 2013-08-06 06:53:41 +09:00
wltsmrz
a99856bec0 Cleanup 2013-08-06 06:17:40 +09:00
wltsmrz
eac195ec18 Cleanup 2013-08-06 04:20:05 +09:00
wltsmrz
ab5d64ff12 Update repository URL 2013-08-03 09:01:55 +09:00
wltsmrz
5f017b2b85 Cleanup, fix jshint warnings 2013-08-03 08:13:36 +09:00
wltsmrz
bb6ec3b5c9 Replace comment 2013-08-03 07:27:59 +09:00
wltsmrz
d870264230 Update untracked files 2013-08-03 07:23:12 +09:00
wltsmrz
aad97c936d Update untracked files 2013-08-03 07:19:15 +09:00
wltsmrz
b78835f195 Typo 2013-08-03 07:18:02 +09:00
wltsmrz
a480e76353 Update Remote constructor comments 2013-08-02 08:27:28 +09:00
wltsmrz
8294c78db4 Greater convenience for payment transactions 2013-08-02 08:17:14 +09:00
Stefan Thomas
c06c74e460 Basic implementation for new path finding API. 2013-07-31 19:54:07 -07:00
jatchili
3ea426d45f Path Set parsing function (not tested yet) 2013-07-31 19:18:42 -07:00
wltsmrz
bc74543ca2 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-08-01 06:04:59 +09:00
wltsmrz
c69966035b Cleanup transaction submission 2013-08-01 06:04:49 +09:00
Stefan Thomas
78b1e4f570 More work on new serialization/parsing functions. Added more tests. 2013-07-30 22:48:07 -07:00
Stefan Thomas
815e2af3cf Fix code indentation. 2013-07-30 21:32:28 -07:00
jatchili
5bc1603f43 begin testing serialization/parsing functions 2013-07-30 20:02:30 -07:00
Stefan Thomas
c48bf4089c Fix serialization of XRP in PathSets. 2013-07-29 18:28:37 -07:00
Stefan Thomas
fd67ea3036 Refactor: Currency parsing. 2013-07-29 18:28:25 -07:00
jatchili
006d1fadce Don't prepend length when you're serializing a Hash256 2013-07-29 17:49:46 -07:00
Stefan Thomas
a1206f6e3f Expose some of the modules related to the binary format. 2013-07-29 13:09:19 -07:00
Stefan Thomas
be2d647d48 Testutils is not used in this testsuite. 2013-07-27 19:46:32 -07:00
wltsmrz
a1bef6248a Accommodate new transaction manager 2013-07-27 05:57:30 +09:00
wltsmrz
2f4a9c2c26 Merge branch 'develop' of https://github.com/ripple/ripple-lib into develop 2013-07-27 04:03:36 +09:00
wltsmrz
342d5a1aa1 Update remote 2013-07-27 04:03:33 +09:00
wltsmrz
a5206d2959 Safer response check, add _remote_address(), attach server to request 2013-07-26 07:25:10 +09:00
wltsmrz
4e876511a3 Connect to servers on an interval 2013-07-26 06:52:20 +09:00
100 changed files with 24634 additions and 4087 deletions

11
.gitignore vendored
View File

@@ -17,7 +17,7 @@
# Ignore object files.
*.o
build
build/ripple*.js
tags
bin/rippled
Debug/*.*
@@ -37,3 +37,12 @@ db/*.db-*
rippled.cfg
validators.txt
test/config.js
# Ignore coverage files
/lib-cov
/src-cov
/coverage.html
/coverage
# Ignore IntelliJ files
.idea

View File

@@ -1,2 +1,3 @@
build
deploy
lib-cov
coverage.html

6
.travis.yml Normal file
View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- "0.10"
script: npm test --coverage
after_success:
- npm run coveralls

View File

@@ -36,11 +36,16 @@ module.exports = function(grunt) {
"src/js/sjcl/core/bn.js",
"src/js/sjcl/core/ecc.js",
"src/js/sjcl/core/srp.js",
"src/js/sjcl-custom/sjcl-ecc-pointextras.js",
"src/js/sjcl-custom/sjcl-secp256k1.js",
"src/js/sjcl-custom/sjcl-ripemd160.js",
"src/js/sjcl-custom/sjcl-extramath.js",
"src/js/sjcl-custom/sjcl-montgomery.js",
"src/js/sjcl-custom/sjcl-validecc.js",
"src/js/sjcl-custom/sjcl-ecdsa-der.js"
"src/js/sjcl-custom/sjcl-ecdsa-canonical.js",
"src/js/sjcl-custom/sjcl-ecdsa-der.js",
"src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js",
"src/js/sjcl-custom/sjcl-jacobi.js"
],
dest: 'build/sjcl.js'
}
@@ -50,7 +55,8 @@ module.exports = function(grunt) {
entry: "./src/js/ripple/index.js",
output: {
library: "ripple"
}
},
cache: true
},
lib: {
output: {
@@ -79,8 +85,8 @@ module.exports = function(grunt) {
tasks: 'concat:sjcl'
},
lib: {
files: 'src/js/*.js',
tasks: 'webpack'
files: 'src/js/ripple/*.js',
tasks: 'webpack:lib_debug'
}
},
dox: {

120
Gulpfile.js Normal file
View File

@@ -0,0 +1,120 @@
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var webpack = require('webpack');
var jshint = require('gulp-jshint');
var map = require('map-stream');
//var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %> - v<%= pkg.version %> - '
+ '<%= new Date().toISOString() %>\n'
+ '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>'
+ '* Copyright (c) <%= new Date().getFullYear() %> <%= pkg.author.name %>;'
+ ' Licensed <%= pkg.license %> */'
var sjclSrc = [
'src/js/sjcl/core/sjcl.js',
'src/js/sjcl/core/aes.js',
'src/js/sjcl/core/bitArray.js',
'src/js/sjcl/core/codecString.js',
'src/js/sjcl/core/codecHex.js',
'src/js/sjcl/core/codecBase64.js',
'src/js/sjcl/core/codecBytes.js',
'src/js/sjcl/core/sha256.js',
'src/js/sjcl/core/sha512.js',
'src/js/sjcl/core/sha1.js',
'src/js/sjcl/core/ccm.js',
// 'src/js/sjcl/core/cbc.js',
// 'src/js/sjcl/core/ocb2.js',
'src/js/sjcl/core/hmac.js',
'src/js/sjcl/core/pbkdf2.js',
'src/js/sjcl/core/random.js',
'src/js/sjcl/core/convenience.js',
'src/js/sjcl/core/bn.js',
'src/js/sjcl/core/ecc.js',
'src/js/sjcl/core/srp.js',
'src/js/sjcl-custom/sjcl-ecc-pointextras.js',
'src/js/sjcl-custom/sjcl-secp256k1.js',
'src/js/sjcl-custom/sjcl-ripemd160.js',
'src/js/sjcl-custom/sjcl-extramath.js',
'src/js/sjcl-custom/sjcl-montgomery.js',
'src/js/sjcl-custom/sjcl-validecc.js',
'src/js/sjcl-custom/sjcl-ecdsa-canonical.js',
'src/js/sjcl-custom/sjcl-ecdsa-der.js',
'src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js',
'src/js/sjcl-custom/sjcl-jacobi.js'
];
gulp.task('concat-sjcl', function() {
return gulp.src(sjclSrc)
.pipe(concat('sjcl.js'))
.pipe(gulp.dest('./build/'));
});
gulp.task('build', [ 'concat-sjcl' ], function(callback) {
webpack({
cache: true,
entry: './src/js/ripple/index.js',
output: {
library: 'ripple',
path: './build/',
filename: [ 'ripple-', '.js' ].join(pkg.version)
},
}, callback);
});
gulp.task('build-min', [ 'build' ], function(callback) {
return gulp.src([ './build/ripple-', '.js' ].join(pkg.version))
.pipe(uglify())
.pipe(rename([ 'ripple-', '-min.js' ].join(pkg.version)))
.pipe(gulp.dest('./build/'));
});
gulp.task('build-debug', [ 'concat-sjcl' ], function(callback) {
webpack({
cache: true,
entry: './src/js/ripple/index.js',
output: {
library: 'ripple',
path: './build/',
filename: [ 'ripple-', '-debug.js' ].join(pkg.version)
},
debug: true,
devtool: 'eval'
}, callback);
});
gulp.task('lint', function() {
gulp.src('src/js/ripple/*.js')
.pipe(jshint())
.pipe(map(function(file, callback) {
if (!file.jshint.success) {
console.log('\nIn', file.path);
file.jshint.results.forEach(function(err) {
if (err && err.error) {
var col1 = err.error.line + ':' + err.error.character;
var col2 = '[' + err.error.reason + ']';
var col3 = '(' + err.error.code + ')';
while (col1.length < 8) {
col1 += ' ';
}
console.log(' ' + [ col1, col2, col3 ].join(' '));
}
});
}
callback(null, file);
}));
});
gulp.task('watch', function() {
gulp.watch('src/js/ripple/*', [ 'build-debug' ]);
});
gulp.task('default', [ 'concat-sjcl', 'build', 'build-debug', 'build-min' ]);

76
HISTORY.md Normal file
View File

@@ -0,0 +1,76 @@
##0.7.37
+ **Deprecations**
1. Removed humanistic amount detection in `transaction.payment`. Passing `1XRP` as the payment amount no longer works.
2. `remote.setServer` uses full server URL rather than hostname. Example: `remote.setServer('wss://s`.ripple.com:443')`
3. Removed constructors for deprecated transaction types from `transaction.js`.
4. Removed `invoiceID` option from `transaction.payment`. Instead, use the `transaction.invoiceID` method.
5. Removed `transaction.transactionManager` getter.
+ Improved multi-server support. Servers are now ranked dynamically, and transactions are broadcasted to all connected servers.
+ Automatically ping connected servers. Client configuration now should contain `ping: <seconds>` to specify the ping interval.
+ Added `transaction.lastLedger` to specify `LastLedgerSequence`. Setting it this way also ensures that the sequence is not bumped on subsequent requests.
+ Added optional `remote.accountTx` binary parsing.
```js
{
binary: true,
parseBinary: false
}
```
+ Added full currency name support, e.g. `Currency.from_json('XRP').to_human({full_name:'Ripples'})` will return `XRP - Ripples`
+ Improved interest bearing currency support, e.g. `Currency.from_human('USD - US Dollar (2.5%pa)')`
+ Improve test coverage
+ Added blob vault client. The vault client facilitates interaction with ripple's namespace and blob vault or 3rd party blob vaults using ripple's blob vault software (https://github.com/ripple/ripple-blobvault). A list of the available functions can be found at [docs/VAULTCLIENT.md](docs/VAULTCLIENT.md)
##0.7.35
+ `LastLedgerSequence` is set by default on outgoing transactions. This refers to the last valid ledger index (AKA sequence) for a transaction. By default, this index is set to the current index (at submission time) plus 8. In theory, this allows ripple-lib to deterministically fail a transaction whose submission request timed out, but whose associated server continues to emit ledger_closed events.
+ Transactions that err with `telINSUF_FEE_P` will be automatically resubmitted. This error indicates that the `Fee` supplied in the transaction submission request was inadquate. Ideally, the `Fee` is tracked by ripple-lib in real-time, and the resubmitted transaction will most likely succeed.
+ Added Transaction.iff(function(callback) { }). Callback expects first argument to be an Error or null, second argument is a boolean which indicates whether or not to proceed with the transaction submission. If an `iff` function is specified, it will be executed prior to every submission of the transaction (including resubmissions).
+ Transactions will now emit `presubmit` and `postsubmit` events. They will be emitted before and after a transaction is submitted, respectively.
+ Added Transaction.summary(). Returns a summary of a transaction in semi-human-readable form. JSON-stringifiable.
+ Remote.requestAccountTx() with `binary: true` will automatically parse transactions.
+ Added Remote.requestAccountTx filter, map, and reduce.
```js
remote.requestAccountTx({
account: 'retc',
ledger_index_min: -1,
ledger_index_max: -1,
limit: 100,
binary: true,
filter: function(transaction) {
return transaction.tx.TransactionType === 'Payment';
},
map: function(transaction) {
return Number(transaction.tx.Amount);
},
reduce: function(a, b) {
return a + b;
},
pluck: 'transactions'
}, console.log)
```
+ Added persistence hooks.
+ General performance improvements, especially for long-running processes.

62
LICENSE
View File

@@ -1,4 +1,4 @@
Copyright (c) 2012,2013 OpenCoin, Inc.
Copyright (c) 2012,2013,2014 Ripple Labs Inc.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
@@ -12,39 +12,39 @@ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------
Some code from Tom Wu:
This software is covered under the following copyright:
/*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
Copyright (c) 2003-2005 Tom Wu
All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
In addition, the following condition applies:
All redistributions must retain an intact copy of this copyright notice
and disclaimer.
Address all questions regarding this license to:

176
README.md
View File

@@ -1,123 +1,97 @@
Ripple JavaScript Library - ripple-lib
======================================
#The Ripple JavaScript Library
This library can connect to the Ripple network via the WebSocket protocol and runs in Node.js as well as in the browser.
[![Build Status](https://travis-ci.org/ripple/ripple-lib.svg?branch=develop)](https://travis-ci.org/ripple/ripple-lib) [![Coverage Status](https://coveralls.io/repos/ripple/ripple-lib/badge.png?branch=develop)](https://coveralls.io/r/ripple/ripple-lib?branch=develop)
* https://ripple.com/wiki/Ripple_JavaScript_library
* https://ripple.com
* https://ripple.com/wiki
[![NPM](https://nodei.co/npm/ripple-lib.png)](https://www.npmjs.org/package/ripple-lib)
##Initializing a remote connection
`ripple-lib` connects to the Ripple network via the WebSocket protocol and runs in Node.js as well as in the browser.
[ripple-lib.remote](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/remote.js) is responsible for managing connections to rippled servers.
###Use ripple-lib for:
+ Connecting to a local or remote rippled in JavaScript (Node.js or browser)
+ Issuing [rippled API](https://ripple.com/wiki/JSON_Messages) requests
+ Listening to events on the Ripple network (transaction, ledger, etc.)
+ Signing and submitting transactions to the Ripple network
###In this file:
1. Overview
2. [Getting `ripple-lib`](README.md#getting-ripple-lib)
3. [Quickstart](README.md#quickstart)
4. [Running tests](https://github.com/ripple/ripple-lib#running-tests)
###For additional documentation see:
1. [The `ripple-lib` Guides (docs/GUIDES.md)](docs/GUIDES.md)
2. [The `ripple-lib` API Reference (docs/REFERENCE.md)](docs/REFERENCE.md)
3. https://ripple.com/wiki/Ripple_JavaScript_library
###Also see:
+ https://ripple.com/wiki
+ https://ripple.com
##Getting `ripple-lib`
**Via npm for Node.js**
```
$ npm install ripple-lib
```
**Build from the source using `grunt`**
```
$ git clone https://github.com/ripple/ripple-lib
$ npm install
$ grunt
```
Then use the minified `build/ripple-*-min.js` in your webpage
##Quickstart
`Remote` ([remote.js](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/remote.js)) is the module responsible for managing connections to `rippled` servers:
```js
/* Loading ripple-lib with Node.js */
var Remote = require('ripple-lib').Remote;
/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;
var remote = new Remote({
trusted: false,
servers: [
{
host: ''
, port: 1111,
, secure: true
}
// see the API Reference for available options
trusted: true,
local_signing: true,
local_fee: true,
fee_cushion: 1.5,
servers: [
{
host: 's1.ripple.com'
, port: 443
, secure: true
}
]
});
remote.connect();
```
remote.connect(function() {
/* remote connected */
Once a connection is formed to any of the supplied servers, a `connect` event is emitted, indicating that the remote is ready to begin fulfilling requests. When there are no more connected servers to fulfill requests, a `disconnect` event is emitted. If you send requests before ripple-lib is connected to any servers, requests are deferred until the `connect` event is received.
```js
var remote = new Remote({ /* options */ }).connect();
remote.request_server_info(function(err, info) { }); // will defer until connected
```
##Remote functions
Each remote function returns a `Request` object. is object is an `EventEmitter`. You may listen for success or failure events from each request, or provide a callback. Example:
```js
var request = remote.request_server_info();
request.on('success', function(res) {
//handle success conditions
});
request.on('error', function(err) {
//handle error conditions
});
request.request();
```
Or:
```js
remote.request_server_info(function(err, res) {
// see the API Reference for available functions
});
```
**request_server_info([callback])**
See [The `ripple-lib` Guides](docs/GUIDES.md) and [The `ripple-lib` API Reference](docs/REFERENCE.md) for walkthroughs and details about all of the available functions and options.
**request_ledger(ledger, [opts], [callback])**
##Running tests
**request_ledger_hash([callback])**
1. Clone the repository
**request_ledger_header([callback])**
2. `cd` into the repository and install dependencies with `npm install`
**request_ledger_current([callback])**
3. `npm test` or `make test` or `node_modules\.bin\mocha test\*-test.js`
**request_ledger_entry(type, [callback])**
**Generating code coverage**
**request_subscribe(streams, [callback])**
**request_unsubscribe(streams, [callback])**
**request_transaction_entry(hash, [callback])**
**request_tx(hash, [callback])**
**request_account_info(accountID, [callback])**
**request_account_lines(accountID, account_index, current, [callback])**
**request_account_offers(accountID, account_index, current, [callback])**
**request_account_tx(opts, [callback])**
**request_book_offers(gets, pays, taker, [callback])**
**request_wallet_accounts(seed, [callback])**
+ requires trusted **remote
**request_sign(secret, tx_json, [callback])**
+ requires trusted **remote
**request_submit([callback])**
**request_account_balance(account, current, [callback])**
**request_account_flags(account, current, [callback])**
**request_owner_count(account, current, [callback])**
**request_ripple_balance(account, issuer, currency, current, [callback])**
**request_ripple_path_find(src_account, dst_account, dst_amount, src_currencies, [callback])**
**request_unl_list([callback])**
**request_unl_add(addr, comment, [callback])**
**request_unl_delete(node, [callback])**
**request_peers([callback])**
**request_connect(ip, port, [callback])**
**transaction()**
+ returns a [Transaction](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/transaction.js) object
ripple-lib uses `istanbul` to generate code coverage. To create a code coverage report, run `npm test --coverage`. The report will be created in `coverage/lcov-report/`.

44
bench/modpow.js Normal file
View File

@@ -0,0 +1,44 @@
var Benchmark;
try {
Benchmark = require('benchmark');
} catch (e) {
console.error("Please install Benchmark.js: npm install benchmark");
process.exit(1);
}
var sjcl = require('../build/sjcl');
var jsbn = require('../src/js/jsbn/jsbn');
var base = "3f70f29d3f3ae354a6d2536ceafba83cfc787cd91e7acd2b6bde05e62beb8295ae18e3f786726f8d034bbc15bf8331df959f59d431736d5f306aaba63dacec279484e39d76db9b527738072af15730e8b9956a64e8e4dbe868f77d1414a8a8b8bf65380a1f008d39c5fabe1a9f8343929342ab7b4f635bdc52532d764701ff3d8072c475c012ff0c59373e8bc423928d99f58c3a6d9f6ab21ee20bc8e8818fc147db09f60c81906f2c6f73dc69725f075853a89f0cd02a30a8dd86b660ccdeffc292f398efb54088c822774445a6afde471f7dd327ef9996296898a5747726ccaeeceeb2e459df98b4128cb5ab8c7cd20c563f960a1aa770f3c81f13f967b6cc";
var exponent = "322e393f76a1c22b147e7d193c00c023afb7c1500b006ff1bc1cc8d391fc38bd";
var modulus = "c7f1bc1dfb1be82d244aef01228c1409c198894eca9e21430f1669b4aa3864c9f37f3d51b2b4ba1ab9e80f59d267fda1521e88b05117993175e004543c6e3611242f24432ce8efa3b81f0ff660b4f91c5d52f2511a6f38181a7bf9abeef72db056508bbb4eeb5f65f161dd2d5b439655d2ae7081fcc62fdcb281520911d96700c85cdaf12e7d1f15b55ade867240722425198d4ce39019550c4c8a921fc231d3e94297688c2d77cd68ee8fdeda38b7f9a274701fef23b4eaa6c1a9c15b2d77f37634930386fc20ec291be95aed9956801e1c76601b09c413ad915ff03bfdc0b6b233686ae59e8caf11750b509ab4e57ee09202239baee3d6e392d1640185e1cd";
var expected = "5b3823974b3eda87286d3f38499de290bd575d8b02f06720acacf3d50950f9ca0ff6b749f3be03913ddca0b291e0b263bdab6c9cb97e4ab47ee9c235ff20931a8ca358726fab93614e2c549594f5c50b1c979b34f840b6d4fc51d6feb2dd072995421d17862cb405e040fc1ed662a3245a1f97bbafa6d1f7f76c7db6a802e3037acdf01ab5053f5da518d6753477193b9c25e1720519dcb9e2f6e70d5786656d356151845a49861dfc40187eff0e85cd18b1f3f3b97c476472edfa090b868b2388edfffecc521c20df8cebb8aacfb3669b020330dd6ea64b2a3067a972b8f249bccc19347eff43893e916f0949bd5789a5cce0f8b7cd87cece909d679345c0d4";
var BigInteger = jsbn.BigInteger;
var jsbnBase = new BigInteger(base, 16);
var jsbnExponent = new BigInteger(exponent, 16);
var jsbnModulus = new BigInteger(modulus, 16);
var bn = sjcl.bn;
var sjclBase = new bn(base);
var sjclExponent = new bn(exponent);
var sjclModulus = new bn(modulus);
var suite = new Benchmark.Suite;
// add tests
suite.add('jsbn#modPow', function() {
jsbnBase.modPow(jsbnExponent, jsbnModulus);
});
suite.add('sjcl#powermodMontgomery', function() {
sjclBase.powermodMontgomery(sjclExponent, sjclModulus);
});
suite.on('cycle', function(event) {
console.log(String(event.target));
});
suite.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
});
// run async
console.log("Running benchmark...");
suite.run({ 'async': false });

47
bin/decode_binary.js Executable file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env node
var SerializedObject = require('../src/js/ripple/serializedobject').SerializedObject;
var argv = process.argv.slice(2);
var blob;
blob = argv.shift();
if (blob === '-') {
read_input(ready);
} else {
ready();
}
function read_input(callback) {
tx_json = '';
process.stdin.on('data', function(data) { tx_json += data; });
process.stdin.on('end', callback);
process.stdin.resume();
}
function ready() {
var valid_arguments = blob;
if (!valid_arguments) {
console.error('Invalid arguments\n');
print_usage();
} else {
decode();
}
}
function print_usage() {
console.log(
'Usage: decode_binary.js <hex_blob>\n\n',
'Example: decode_binary.js 120000240000000161D6871AFD498D00000000000000000000000000005553440000000000550FC62003E785DC231A1058A05E56E3F09CF4E668400000000000000A732102AE75B908F0A95F740A7BFA96057637E5C2170BC8DAD13B2F7B52AE75FAEBEFCF811450F97A072F1C4357F1AD84566A609479D927C9428314550FC62003E785DC231A1058A05E56E3F09CF4E6'
);
};
function decode() {
buffer = new SerializedObject(blob);
console.log(buffer.to_json());
};
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,65 +1,96 @@
#!/usr/bin/node
#!/usr/bin/env node
var Transaction = require('../src/js/ripple/transaction').Transaction;
var cursor = 2;
var argv = process.argv.slice(2);
var verbose;
var secret;
var tx_json;
var usage = function () {
if (~argv.indexOf('-v')){
argv.splice(argv.indexOf('-v'), 1);
verbose = true;
}
secret = argv.shift();
tx_json = argv.shift();
if (tx_json === '-') {
read_input(ready);
} else {
ready();
}
function read_input(callback) {
tx_json = '';
process.stdin.on('data', function(data) { tx_json += data; });
process.stdin.on('end', callback);
process.stdin.resume();
}
function ready() {
var valid_arguments = secret && tx_json;
if (!valid_arguments) {
console.error('Invalid arguments\n');
print_usage();
} else {
var valid_json = true;
try {
tx_json = JSON.parse(tx_json);
} catch(exception) {
valid_json = false;
}
if (!valid_json) {
console.error('Invalid JSON\n');
print_usage();
} else {
sign_transaction();
}
}
}
function print_usage() {
console.log(
"Usage: rsign.js <secret> <json>\n"
+ " Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC '{ \"TransactionType\" : \"Payment\", \"Account\" : \"r3P9vH81KBayazSTrQj6S25jW6kDb779Gi\", \"Destination\" : \"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV\", \"Amount\" : \"200000000\", \"Fee\" : \"10\", \"Sequence\" : \"1\" }'"
'Usage: rsign.js <secret> <json>\n\n',
'Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC',
JSON.stringify({
TransactionType: 'Payment',
Account: 'r3P9vH81KBayazSTrQj6S25jW6kDb779Gi',
Destination: 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV',
Amount: '200000000',
Fee: '10',
Sequence: 1
})
);
};
if (process.argv.length > cursor && process.argv[cursor] === "-v")
{
verbose = true;
cursor++;
}
function sign_transaction() {
var tx = new Transaction();
if (process.argv.length > cursor)
{
secret = process.argv[cursor++];
}
tx.tx_json = tx_json;
tx._secret = secret;
tx.complete();
if (process.argv.length > cursor)
{
tx_json = JSON.parse(process.argv[cursor++]);
}
var unsigned_blob = tx.serialize().to_hex();
var unsigned_hash = tx.signingHash();
tx.sign();
if (process.argv.length !== cursor || !secret || !tx_json)
{
usage();
}
else
{
var tx = new Transaction();
if (verbose) {
var sim = { };
tx.tx_json = tx_json;
tx._secret = secret;
tx.complete();
sim.tx_blob = tx.serialize().to_hex();
sim.tx_json = tx.tx_json;
sim.tx_signing_hash = unsigned_hash;
sim.tx_unsigned = unsigned_blob;
var unsigned = tx.serialize().to_hex();
tx.sign();
if (verbose)
{
var sim = {};
sim.tx_blob = tx.serialize().to_hex();
sim.tx_json = tx.tx_json;
sim.tx_signing_hash = tx.signing_hash().to_hex();
sim.tx_unsigned = unsigned;
console.log(JSON.stringify(sim, undefined, 2));
}
else
{
console.log(tx.serialize().to_hex());
}
}
console.log(JSON.stringify(sim, null, 2));
} else {
console.log(tx.serialize().to_hex());
}
};
// vim:sw=2:sts=2:ts=8:et

26
bin/validate_address.js Executable file
View File

@@ -0,0 +1,26 @@
#!/usr/bin/env node
var UInt160 = require('../').UInt160;
var address = process.argv[2];
if (address === '-') {
readInput(validateAddress);
} else {
validateAddress(address);
}
function readInput(callback) {
var result = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
result += data;
});
process.stdin.on('end', function() {
callback(result);
});
};
function validateAddress(address) {
process.stdout.write((UInt160.is_valid(address.trim()) ? '0' : '1') + '\r\n');
};

4550
build/sjcl.js Normal file

File diff suppressed because it is too large Load Diff

201
docs/GUIDES.md Normal file
View File

@@ -0,0 +1,201 @@
#`ripple-lib` Guides
This file provides step-by-step walkthroughs for some of the most common usages of `ripple-lib`.
###Guides in this document:
1. [Connecting to the Ripple network with `Remote`](GUIDES.md#1-connecting-to-the-ripple-network-with-remote)
2. [Using `Remote` functions and `Request` objects](GUIDES.md#2-using-remote-functions-and-request-objects)
3. [Submitting a payment to the network](GUIDES.md#3-submitting-a-payment-to-the-network)
* [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees)
4. [Submitting a trade offer to the network](GUIDES.md#4-submitting-a-trade-offer-to-the-network)
5. [Listening to the network](GUIDES.md#5-listening-to-the-network)
###Also see:
1. [The `ripple-lib` README](../README.md)
2. [The `ripple-lib` API Reference](REFERENCE.md)
##1. Connecting to the Ripple network with `Remote`
1. [Get `ripple-lib`](README.md#getting-ripple-lib)
2. Load the `ripple-lib` module into a Node.js file or webpage:
```js
/* Loading ripple-lib with Node.js */
var Remote = require('ripple-lib').Remote;
/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;
```
3. Create a new `Remote` and connect to the network:
```js
var remote = new Remote({options});
remote.connect(function() {
/* remote connected, use some remote functions here */
});
```
__NOTE:__ See the API Reference for available [`Remote` options](REFERENCE.md#1-remote-options)
4. You're connected! Read on to see what to do now.
##2. Using `Remote` functions and `Request` objects
All `Remote` functions return a `Request` object.
A `Request` is an `EventEmitter` so you can listen for success or failure events -- or, instead, you can provide a callback to the `Remote` function.
Here is an example, using `request_server_info()`, of how `Remote` functions can be used with event listeners (the first code block) or with a callback (the second block):
+ Using a `Remote` function with `Request` event listeners:
```js
var request = remote.request_server_info();
request.on('success', function(res) {
//handle success
});
request.on('error', function(err) {
//handle error
});
request.request(); // this triggers the request if it has not already been sent to the server
```
+ Using a `Remote` function with a callback:
```js
remote.request_server_info(function(err, res) {
if (err) {
//handle error
} else {
//handle success
}
});
```
__NOTE:__ See the API Reference for available [`Remote` functions](REFERENCE.md#2-remote-functions)
##3. Submitting a payment to the network
Submitting a payment transaction to the Ripple network involves connecting to a `Remote`, creating a transaction, signing it with the user's secret, and submitting it to the `rippled` server. Note that the `Amount` module is used to convert human-readable amounts like '1XRP' or '10.50USD' to the type of Amount object used by the Ripple network.
```js
/* Loading ripple-lib Remote and Amount modules in Node.js */
var Remote = require('ripple-lib').Remote;
var Amount = require('ripple-lib').Amount;
/* Loading ripple-lib Remote and Amount modules in a webpage */
// var Remote = ripple.Remote;
// var Amount = ripple.Amount;
var MY_ADDRESS = 'rrrMyAddress';
var MY_SECRET = 'secret';
var RECIPIENT = 'rrrRecipient';
var AMOUNT = Amount.from_human('1XRP');
var remote = new Remote({ /* Remote options */ });
remote.connect(function() {
remote.set_secret(MY_ADDRESS, MY_SECRET);
var transaction = remote.transaction();
transaction.payment({
from: MY_ADDRESS,
to: RECIPIENT,
amount: AMOUNT
});
transaction.submit(function(err, res) {
/* handle submission errors / success */
});
});
```
###A note on transaction fees
A full description of network transaction fees can be found on the [Ripple Wiki](https://ripple.com/wiki/Transaction_Fee).
In short, transaction fees are very small amounts (on the order of ~10) of [XRP drops](https://ripple.com/wiki/Ripple_credits#Notes_on_drops) spent and destroyed with every transaction. They are largely used to account for network load and prevent spam. With `ripple-lib`, transaction fees are calculated locally by default and the fee you are willing to pay is submitted along with your transaction.
Since the fee required for a transaction may change between the time when the original fee was calculated and the time when the transaction is submitted, it is wise to use the [`fee_cushion`](REFERENCE.md#1-remote-options) to ensure that the transaction will go through. For example, suppose the original fee calculated for a transaction was 10 XRP drops but at the instant the transaction is submitted the server is experiencing a higher load and it has raised its minimum fee to 12 XRP drops. Without a `fee_cusion`, this transaction would not be processed by the server, but with a `fee_cusion` of, say, 1.5 it would be processed and you would just pay the 2 extra XRP drops.
The [`max_fee`](REFERENCE.md#1-remote-options) option can be used to avoid submitting a transaction to a server that is charging unreasonably high fees.
##4. Submitting a trade offer to the network
Submitting a trade offer to the network is similar to submitting a payment transaction. Here is an example for a trade that expires in 24 hours where you are offering to sell 1 USD in exchange for 100 XRP:
```js
/* Loading ripple-lib Remote and Amount modules in Node.js */
var Remote = require('ripple-lib').Remote;
var Amount = require('ripple-lib').Amount;
/* Loading ripple-lib Remote and Amount modules in a webpage */
// var Remote = ripple.Remote;
// var Amount = ripple.Amount;
var MY_ADDRESS = 'rrrMyAddress';
var MY_SECRET = 'secret';
var BUY_AMOUNT = Amount.from_human('100XRP');
var SELL_AMOUNT = Amount.from_human('1USD');
// EXPIRATION must be a Date object, leave undefined to submit offer that won't expire
var now = new Date();
var tomorrow = new Date(now.getTime() + (24 * 60 * 60 * 1000));
var EXPIRATION = tomorrow;
var remote = new Remote({ /* Remote options */ });
remote.connect(function() {
remote.set_secret(MY_ADDRESS, MY_SECRET);
var transaction = remote.transaction();
transaction.offer_create({
from: MY_ADDRESS,
buy: BUY_AMOUNT,
sell: SELL_AMOUNT,
expiration: EXPIRATION
});
transaction.submit(function(err, res) {
/* handle submission errors / success */
});
});
```
##5. Listening to the network
In some (relatively rare) cases you may want to subscribe to the network event feed and listen for transactions and the ledger closings. [Ripple.com](http://www.ripple.com) uses this feature of `ripple-lib` to display the live feed on the top of each page and the ledger closing visualization on the [Developers page](http://ripple.com/devs).
```js
/* Loading ripple-lib with Node.js */
var Remote = require('ripple-lib').Remote;
/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;
var remote = new Remote({options});
remote.connect(function() {
remote.on('transaction_all', transactionListener);
remote.on('ledger_closed', ledgerListener);
});
function transactionListener (transaction_data) {
// handle transaction_data
// see https://ripple.com/wiki/RPC_API#transactions_stream_messages for the format of transaction_data
}
function ledgerListener (ledger_data) {
// handle ledger_data
// see https://ripple.com/wiki/RPC_API#ledger_stream_messages for the format of ledger_data
}
```
* https://ripple.com/wiki/RPC_API#transactions_stream_messages
* https://ripple.com/wiki/RPC_API#ledger_stream_messages

258
docs/REFERENCE.md Normal file
View File

@@ -0,0 +1,258 @@
#`ripple-lib` API Reference
__(More examples coming soon!)__
###In this document:
1. [`Remote` options](REFERENCE.md#1-remote-options)
2. [`Remote` functions](REFERENCE.md#2-remote-functions)
+ [Server info functions](REFERENCE.md#server-info-functions)
+ [Ledger query functions](REFERENCE.md#ledger-query-functions)
+ [Transaction query functions](REFERENCE.md#transaction-query-functions)
+ [Account query functions](REFERENCE.md#account-query-functions)
+ [Order book query functions](REFERENCE.md#order-book-query-functions)
+ [Transaction submission functions](REFERENCE.md#transaction-submission-functions)
3. [`Transaction` events](REFERENCE.md#3-transaction-events)
4. [`Amount` objects](REFERENCE.md#4-amount-objects)
###Also see:
1. [The `ripple-lib` README](../README.md)
2. [The `ripple-lib` GUIDES](GUIDES.md)
#1. `Remote` options
```js
/* Loading ripple-lib with Node.js */
var Remote = require('ripple-lib').Remote;
/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;
var remote = new Remote({options});
```
A new `Remote` can be created with the following options:
+ `trace` Log all of the events emitted (boolean)
+ `max_listeners` Set maxListeners for remote; prevents EventEmitter warnings (number)
+ `connection_offset` Connect to remote servers on supplied interval (number in seconds)
+ `trusted` truthy, if remote is trusted (boolean)
+ `local_fee` Set whether the transaction fee range will be set locally (boolean, default is true, see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees))
+ `fee_cushion` Extra fee multiplier to account for async fee changes (number, e.g. 1.5, see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees))
+ `max_fee` Maximum acceptable transaction fee (number in [XRP drops](https://ripple.com/wiki/Ripple_credits#Notes_on_drops), see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees))
+ `servers` Array of server objects of the following form:
```js
{
host: <string>
, port: <number>
, secure: <boolean>
}
```
#2. `Remote` functions
##Server info functions
**[request_server_info([callback])](https://ripple.com/wiki/RPC_API#server_info)**
Returns information about the state of the server. If you are connected to multiple servers and want to select by a particular host, use `request.set_server`. Example:
```js
var request = remote.request_server_info();
request.set_server('my.hostname');
request.callback(function(err, res) {
});
request.request();
```
**[request_unl_list([callback])](https://ripple.com/wiki/RPC_API#unl_list)**
**[request_unl_add(addr, comment, [callback])](https://ripple.com/wiki/RPC_API#unl_add)**
**[request_unl_delete(node, [callback])](https://ripple.com/wiki/RPC_API#unl_delete)**
**[request_peers([callback])](https://ripple.com/wiki/RPC_API#peers)**
**[request_connect(ip, port, [callback])](https://ripple.com/wiki/RPC_API#connect)**
##Ledger query functions
**[request_ledger(ledger, [opts], [callback])](https://ripple.com/wiki/RPC_API#ledger)**
**request_ledger_header([callback])**
**[request_ledger_current([callback])](https://ripple.com/wiki/RPC_API#ledger_current)**
**[request_ledger_entry(type, [callback])](https://ripple.com/wiki/RPC_API#ledger_entry)**
**[request_subscribe(streams, [callback])](https://ripple.com/wiki/RPC_API#subscribe)**
Start receiving selected streams from the server.
**[request_unsubscribe(streams, [callback])](https://ripple.com/wiki/RPC_API#unsubscribe)**
Stop receiving selected streams from the server.
##Transaction query functions
**[request_transaction_entry(hash, [ledger_hash], [callback])](https://ripple.com/wiki/RPC_API#transaction_entry)**
Searches a particular ledger for a transaction hash. Default ledger is the open ledger.
**[request_tx(hash, [callback])](https://ripple.com/wiki/RPC_API#tx)**
Searches ledger history for validated transaction hashes.
##Account query functions
**[request_account_info(account, [callback])](https://ripple.com/wiki/RPC_API#account_info)**
Return information about the specified account.
```
{
ledger_current_index: <number>,
account_data: {
Account: <string>,
Balance: <number>,
Flags: <number>,
LedgerEntryType: <string>,
OwnerCount: <number>,
PreviousTxnID: <string>,
PreviousTxnLgrSeq: <number>,
Sequence: <number> ,
index: <string>
}
}
```
**[request_account_lines(accountID, account_index, current, [callback])](https://ripple.com/wiki/RPC_API#account_lines)**
**[request_account_offers(accountID, account_index, current, [callback])](https://ripple.com/wiki/RPC_API#account_offers)**
Return the specified account's outstanding offers.
**[request_account_tx(opts, [callback])](https://ripple.com/wiki/RPC_API#account_tx)**
Fetch a list of transactions that applied to this account.
Options:
+ `account`
+ `ledger_index_min` *deprecated, -1*
+ `ledger_index_max` *deprecated, -1*
+ `binary` *false*
+ `count` *false*
+ `descending` *false*
+ `offset` *0*
+ `limit`
+ `forward` *false*
+ `fwd_marker`
+ `rev_marker`
**[request_wallet_accounts(seed, [callback])](https://ripple.com/wiki/RPC_API#wallet_accounts)**
Return a list of accounts for a wallet.
+ requires trusted remote
**request_account_balance(account, ledger, [callback])**
Get the balance for an account. Returns an [Amount](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/amount.js) object.
**request_account_flags(account, current, [callback])**
Return the flags for an account.
**request_owner_count(account, current, [callback])**
Return the owner count for an account.
**request_ripple_balance(account, issuer, currency, current, [callback])**
Return a request to get a ripple balance
##Order book query functions
**[request_book_offers(gets, pays, taker, [callback])](https://ripple.com/wiki/RPC_API#book_offers)**
Return the offers for an order book as one or more pages.
```js
var request = remote.request_book_offers({
gets: {
'currency':'XRP'
},
pays: {
'currency':'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
});
request.request();
```
##Transaction submission functions
**[request_sign(secret, tx_json, [callback])](https://ripple.com/wiki/RPC_API#sign)**
Sign a transaction.
+ requires trusted remote
**[request_submit([callback])](https://ripple.com/wiki/RPC_API#submit)**
Submit a transaction to the network. This command is used internally to submit transactions with a greater degree of reliability. See [Submitting a payment to the network](GUIDES.md#3-submitting-a-payment-to-the-network) for details.
**[request_ripple_path_find(src_account, dst_account, dst_amount, src_currencies, [callback])](https://ripple.com/wiki/RPC_API#path_find)**
**transaction([destination], [source], [amount], [callback])**
Returns a [Transaction](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/transaction.js) object
#3. Transaction events
[Transaction](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/transaction.js) objects are EventEmitters. They may emit the following events.
+ `final` Transaction has erred or succeeded. This event indicates that the transaction has finished processing.
+ `error` Transaction has erred. This event is a final state.
+ `success` Transaction succeeded. This event is a final state.
+ `submitted` Transaction has been submitted to the network. The submission may result in a remote error or success.
+ `proposed` Transaction has been submitted *successfully* to the network. The transaction at this point is awaiting validation in a ledger.
+ `timeout` Transaction submission timed out. The transaction will be resubmitted.
+ `resubmit` Transaction is beginning resubmission.
+ `fee_adjusted` Transaction fee has been adjusted during its pending state. The transaction fee will only be adjusted if the remote is configured for local fees, which it is by default.
+ `abort` Transaction has been aborted. Transactions are only aborted by manual calls to `#abort`.
+ `missing` Four ledgers have closed without detecting validated transaction
+ `lost` Eight ledgers have closed without detecting validated transaction. Consider the transaction lost and err/finalize.
#4. Amount objects
Coming Soon

168
docs/VAULTCLIENT.md Normal file
View File

@@ -0,0 +1,168 @@
ripple-vault-client
===================
A javascript / http client to interact with Ripple Vault servers.
The purpose of this tool is to enable applications in any javascript
environment to login with the ripple vault and access the decrypted
data stored using credentials originally obtained at ripple.com
## Vault Client Usage
vaultClient = new ripple.VaultClient(domain);
vaultClient.getAuthInfo(username, callback);
vaultClient.getRippleName(address, url, callback);
vaultClient.exists(username, callback);
vaultClient.login(username, password, callback);
vaultClient.relogin(id, cryptKey, callback);
vaultClient.unlock(username, password, encryptSecret, callback);
vaultClient.loginAndUnlock(username, password, callback);
vaultClient.register(options, callback);
vaultClient.deleteBlob(options, callback);
vaultClient.recoverBlob(options, callback);
vaultClient.rename(options, callback);
vaultClient.changePassword(options, callback);
vaultClient.verify(username, token, callback);
vaultClient.resendEmail(options, callback);
vaultClient.updateProfile(options, fn);
# Blob Methods
blob.encrypt();
blob.decrypt(encryptedBlob);
blob.encryptSecret(encryptionKey);
blob.decryptSecret(encryptionKey, secret);
blob.set(pointer, value, callback);
blob.unset(pointer, callback);
blob.extend(pointer, value, callback);
blob.unshift(pointer, value, callback);
blob.filter(pointer, field, value, subcommands, callback);
## Identity Vault
The identity vault stores identity information inside the encrypted
blob vault. The identity fields can be additionally encrypted with the
unlock key, that encrypts the secret, for added security. Methods are
accessed from the 'identity' property of the blob object.
# Identity fields
+ name
+ entityType (individual, corporation, organization)
+ email
+ phone
+ address
+ contact
+ line1
+ line2
+ city
+ postalCode
+ region - state/province/region
+ country
+ nationalID
+ number
+ type (ssn, taxID, passport, driversLicense, other)
+ country - issuing country
+ birthday
+ birthplace
# Identity Methods
blob.identity.set(pointer, key, value, callback);
blob.identity.unset(pointer, key, callback);
blob.identity.get(pointer, key);
blob.identity.getAll(key);
blob.identity.getFullAddress(key); //get text string of full address
## Spec Tests
Run `npm test` to test the high-level behavior specs
Ripple Txt
✓ should get the content of a ripple.txt file from a given domain
✓ should get currencies from a ripple.txt file for a given domain
✓ should get the domain from a given url
AuthInfo
✓ should get auth info
VaultClient
#initialization
✓ should be initialized with a domain
✓ should default to ripple.com without a domain
#exists
✓ should determine if a username exists on the domain
#login
✓ with username and password should retrive the blob, crypt key, and id
#relogin
✓ should retrieve the decrypted blob with blob vault url, id, and crypt key
#unlock
✓ should access the wallet secret using encryption secret, username and password
#loginAndUnlock
✓ should get the decrypted blob and decrypted secret given name and password
#register
✓ should create a new blob
#deleteBlob
✓ should remove an existing blob
#updateProfile
✓ should update profile parameters associated with a blob
Blob
#set
#extend
#unset
#unshift
#filter
#consolidate
#rename
✓ should change the username of a blob
#changePassword
✓ should change the password and keys of a blob
#recoverBlob
✓ should recover the blob given a username and secret
#verifyEmail
✓ should verify an email given a username and token
#resendVerifcationEmail
✓ should resend a verification given options
identity
#identity_set
#identity_get
#identity_getAll
#identity_getFullAddress
#identity_unset

View File

@@ -1,39 +1,48 @@
{
"name": "ripple-lib",
"version": "0.7.18",
"version": "0.7.37",
"description": "Ripple JavaScript client library",
"files": [
"src/js/ripple/*.js",
"build/sjcl.js",
"bin/rsign.js"
"src/js/*",
"bin/*",
"build/*",
"test/*",
"Makefile",
"Gulpfile.js"
],
"main": "src/js/ripple",
"directories": {
"test": "test"
},
"dependencies": {
"async": "~0.2.9",
"ws": "~0.4.27",
"extend": "~1.1.3",
"simple-jsonrpc": "~0.0.2",
"jshint-loader": "~0.5.0"
"async": "~0.8.0",
"ws": "~0.4.31",
"extend": "~1.2.1",
"lru-cache": "~2.5.0",
"superagent": "^0.18.0",
"gulp-uglify": "~0.3.0",
"gulp-rename": "~1.2.0"
},
"devDependencies": {
"grunt": "~0.4.1",
"grunt-cli": "~0.1.9",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-watch": "~0.4.4",
"grunt-webpack": "~0.10.5",
"grunt-dox": "~0.5.0",
"buster": "~0.6.12"
"mocha": "~1.14.0",
"gulp": "~3.6.2",
"gulp-concat": "~2.2.0",
"gulp-jshint": "~1.5.5",
"webpack": "~1.1.11",
"map-stream": "~0.1.0",
"istanbul": "~0.2.10",
"coveralls": "~2.10.0",
"nock": "^0.34.1"
},
"scripts": {
"test": "node_modules/buster/bin/buster-test",
"build": "node_modules/.bin/grunt"
"build": "node_modules/.bin/gulp",
"pretest": "node_modules/.bin/gulp concat-sjcl",
"test": "./node_modules/.bin/istanbul test -x build/sjcl.js -x src/js/jsbn/* ./node_modules/.bin/_mocha -- --reporter spec test/*-test.js",
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
},
"repository": {
"type": "git",
"url": "git://github.com/rippleFoundation/ripple-lib.git"
"url": "git://github.com/ripple/ripple-lib.git"
},
"readmeFilename": "README.md",
"engines": {

49
scripts/verify_ledger_json.js Executable file
View File

@@ -0,0 +1,49 @@
var fs = require('fs');
var Ledger = require('../src/js/ripple/ledger').Ledger;
function parse_options(from, flags) {
var argv = from.slice(),
opts = {argv:argv};
flags.forEach(function(f) {
// Do we have the flag?
var flag_index = argv.indexOf('--' + f);
// normalize the name of the flag
f = f.replace('-', '_');
// opts has Boolean value for normalized flag key
opts[f] = !!~flag_index;
if (opts[f]) {
// remove the flag from the argv
argv.splice(flag_index, 1);
}
});
return opts;
}
var opts = parse_options(process.argv.slice(2), // remove `node` and `this.js`
['sanity-test']);
if (opts.argv.length < 1) {
console.error("Usage: scripts/verify_ledger_json path/to/ledger.json");
console.error(" optional: --sanity-test (json>binary>json>binary)");
process.exit(1);
}
var json = fs.readFileSync(opts.argv[0], 'utf-8');
var ledger = Ledger.from_json(JSON.parse(json));
// This will serialize each accountState object to binary and then back to json
// before finally serializing for hashing. This is mostly to expose any issues
// with ripple-libs binary <--> json codecs.
if (opts.sanity_test) {
console.log("All accountState nodes will be processed from " +
"json->binary->json->binary. This may take some time " +
"with large ledgers.");
}
console.log("Transaction hash in header: " + ledger.ledger_json.transaction_hash);
console.log("Calculated transaction hash: " + ledger.calc_tx_hash().to_hex());
console.log("Account state hash in header: " + ledger.ledger_json.account_hash);
console.log("Calculated account state hash: " + ledger.calc_account_hash(
{sanity_test:opts.sanity_test})
.to_hex());

View File

@@ -1,15 +1,8 @@
// Derived from Tom Wu's jsbn code.
//
// Changes made for clean up and to package as a node.js module.
// Copyright (c) 2005-2009 Tom Wu
// Copyright (c) 2005 Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
// Basic JavaScript BN library - subset useful for RSA encryption.
// Extended JavaScript BN functions, required for RSA private ops.
// Version 1.1: new BigInteger("0", 10) returns "proper" zero
// Version 1.2: square() API, isProbablePrime fix
// Bits per digit
var dbits;
@@ -19,15 +12,15 @@ var canary = 0xdeadbeefcafe;
var j_lm = ((canary&0xffffff)==0xefcafe);
// (public) Constructor
var BigInteger = function BigInteger(a,b,c) {
function BigInteger(a,b,c) {
if(a != null)
if("number" == typeof a) this.fromNumber(a,b,c);
else if(b == null && "string" != typeof a) this.fromString(a,256);
else this.fromString(a,b);
};
}
// return new, unset BigInteger
var nbi = function nbi() { return new BigInteger(null); };
function nbi() { return new BigInteger(null); }
// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
@@ -74,7 +67,6 @@ function am3(i,x,w,j,c,n) {
}
return c;
}
if(j_lm && 'undefined' !== typeof navigator && (navigator.appName == "Microsoft Internet Explorer")) {
BigInteger.prototype.am = am2;
dbits = 30;
@@ -126,7 +118,7 @@ function bnpFromInt(x) {
this.t = 1;
this.s = (x<0)?-1:0;
if(x > 0) this[0] = x;
else if(x < -1) this[0] = x+DV;
else if(x < -1) this[0] = x+this.DV;
else this.t = 0;
}
@@ -1122,6 +1114,7 @@ function bnpMillerRabin(t) {
return true;
}
// protected
BigInteger.prototype.chunkSize = bnpChunkSize;
BigInteger.prototype.toRadix = bnpToRadix;
@@ -1137,7 +1130,31 @@ BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
BigInteger.prototype.modInt = bnpModInt;
BigInteger.prototype.millerRabin = bnpMillerRabin;
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
BigInteger.prototype.clone = bnClone;
BigInteger.prototype.intValue = bnIntValue;
BigInteger.prototype.byteValue = bnByteValue;
@@ -1175,6 +1192,10 @@ BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
// JSBN-specific extension
BigInteger.prototype.square = bnSquare;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
// BigInteger interfaces not implemented in jsbn:
// BigInteger(int signum, byte[] magnitude)
@@ -1183,37 +1204,7 @@ BigInteger.prototype.square = bnSquare;
// int hashCode()
// long longValue()
// static BigInteger valueOf(long val)
// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
BigInteger.valueOf = nbi;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
exports.nbi = nbi;
exports.BigInteger = BigInteger;
// vim:sw=2:sts=2:ts=8:et
exports.BigInteger = BigInteger;

View File

@@ -3,24 +3,32 @@
// You should not instantiate this class yourself, instead use Remote#account.
//
// Events:
// wallet_clean : True, iff the wallet has been updated.
// wallet_dirty : True, iff the wallet needs to be updated.
// balance : The current stamp balance.
// wallet_clean : True, iff the wallet has been updated.
// wallet_dirty : True, iff the wallet needs to be updated.
// balance: The current stamp balance.
// balance_proposed
//
// var network = require("./network.js");
// var network = require('./network.js');
var async = require('async');
var util = require('util');
var extend = require('extend');
var EventEmitter = require('events').EventEmitter;
var Amount = require('./amount').Amount;
var UInt160 = require('./uint160').UInt160;
var TransactionManager = require('./transactionmanager').TransactionManager;
var sjcl = require('./utils').sjcl;
var Base = require('./base').Base;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
/**
* @constructor Account
* @param {Remote} remote
* @param {String} account
*/
var Amount = require('./amount').Amount;
var UInt160 = require('./uint160').UInt160;
var extend = require('extend');
var Account = function (remote, account) {
function Account(remote, account) {
EventEmitter.call(this);
var self = this;
this._remote = remote;
@@ -30,48 +38,67 @@ var Account = function (remote, account) {
// Ledger entry object
// Important: This must never be overwritten, only extend()-ed
this._entry = {};
this._entry = { };
this.on('newListener', function (type, listener) {
if (Account.subscribe_events.indexOf(type) !== -1) {
if (!self._subs && 'open' === self._remote._online_state) {
function listenerAdded(type, listener) {
if (~Account.subscribeEvents.indexOf(type)) {
if (!self._subs && self._remote._connected) {
self._remote.request_subscribe()
.accounts(self._account_id)
.request();
.add_account(self._account_id)
.broadcast();
}
self._subs += 1;
self._subs += 1;
}
});
};
this.on('removeListener', function (type, listener) {
if (Account.subscribe_events.indexOf(type) !== -1) {
self._subs -= 1;
this.on('newListener', listenerAdded);
if (!self._subs && 'open' === self._remote._online_state) {
function listenerRemoved(type, listener) {
if (~Account.subscribeEvents.indexOf(type)) {
self._subs -= 1;
if (!self._subs && self._remote._connected) {
self._remote.request_unsubscribe()
.accounts(self._account_id)
.request();
.add_account(self._account_id)
.broadcast();
}
}
});
};
this._remote.on('prepare_subscribe', function (request) {
if (self._subs) request.accounts(self._account_id);
});
this.on('removeListener', listenerRemoved);
function attachAccount(request) {
if (self._account.is_valid() && self._subs) {
request.add_account(self._account_id);
}
};
this._remote.on('prepare_subscribe', attachAccount);
function handleTransaction(transaction) {
if (!transaction.mmeta) {
return;
}
this.on('transaction', function (msg) {
var changed = false;
msg.mmeta.each(function (an) {
if (an.entryType === 'AccountRoot' &&
an.fields.Account === self._account_id) {
transaction.mmeta.each(function(an) {
var isAccount = an.fields.Account === self._account_id;
var isAccountRoot = isAccount && (an.entryType === 'AccountRoot');
if (isAccountRoot) {
extend(self._entry, an.fieldsNew, an.fieldsFinal);
changed = true;
}
});
if (changed) {
self.emit('entry', self._entry);
}
});
};
this.on('transaction', handleTransaction);
this._transactionManager = new TransactionManager(this);
return this;
};
@@ -81,10 +108,10 @@ util.inherits(Account, EventEmitter);
/**
* List of events that require a remote subscription to the account.
*/
Account.subscribe_events = ['transaction', 'entry'];
Account.prototype.to_json = function ()
{
Account.subscribeEvents = [ 'transaction', 'entry' ];
Account.prototype.toJson = function() {
return this._account.to_json();
};
@@ -93,36 +120,133 @@ Account.prototype.to_json = function ()
*
* Note: This does not tell you whether the account exists in the ledger.
*/
Account.prototype.is_valid = function ()
{
Account.prototype.isValid = function() {
return this._account.is_valid();
};
/**
* Request account info
*
* @param {Function} callback
*/
Account.prototype.getInfo = function(callback) {
return this._remote.request_account_info(this._account_id, callback);
};
/**
* Retrieve the current AccountRoot entry.
*
* To keep up-to-date with changes to the AccountRoot entry, subscribe to the
* "entry" event.
* 'entry' event.
*
* @param {function (err, entry)} callback Called with the result
* @param {Function} callback
*/
Account.prototype.entry = function (callback)
{
Account.prototype.entry = function(callback) {
var self = this;
var callback = typeof callback === 'function' ? callback : function(){};
self._remote.request_account_info(this._account_id)
.on('success', function (e) {
extend(self._entry, e.account_data);
function accountInfo(err, info) {
if (err) {
callback(err);
} else {
extend(self._entry, info.account_data);
self.emit('entry', self._entry);
callback(null, info);
}
};
if ("function" === typeof callback) {
callback(null, e);
this.getInfo(accountInfo);
return this;
};
Account.prototype.getNextSequence = function(callback) {
var callback = typeof callback === 'function' ? callback : function(){};
function isNotFound(err) {
return err && typeof err === 'object'
&& typeof err.remote === 'object'
&& err.remote.error === 'actNotFound';
};
function accountInfo(err, info) {
if (isNotFound(err)) {
// New accounts will start out as sequence zero
callback(null, 0);
} else if (err) {
callback(err);
} else {
callback(null, info.account_data.Sequence);
}
};
this.getInfo(accountInfo);
return this;
};
/**
* Retrieve this account's Ripple trust lines.
*
* To keep up-to-date with changes to the AccountRoot entry, subscribe to the
* 'lines' event. (Not yet implemented.)
*
* @param {function(err, lines)} callback Called with the result
*/
Account.prototype.lines = function(callback) {
var self = this;
var callback = typeof callback === 'function' ? callback : function(){};
function accountLines(err, res) {
if (err) {
callback(err);
} else {
self._lines = res.lines;
self.emit('lines', self._lines);
callback(null, res);
}
}
this._remote.requestAccountLines(this._account_id, accountLines);
return this;
};
/**
* Retrieve this account's single trust line.
*
* @param {string} currency Currency
* @param {string} address Ripple address
* @param {function(err, line)} callback Called with the result
* @returns {Account}
*/
Account.prototype.line = function(currency, address, callback) {
var self = this;
var callback = typeof callback === 'function' ? callback : function(){};
self.lines(function(err, data) {
if (err) {
return callback(err);
}
var line;
top:
for (var i=0; i<data.lines.length; i++) {
var l = data.lines[i];
if (l.account === address && l.currency === currency) {
line = l;
break top;
}
})
.on('error', function (e) {
callback(e);
})
.request();
}
callback(null, line);
});
return this;
};
@@ -132,17 +256,141 @@ Account.prototype.entry = function (callback)
*
* This is only meant to be called by the Remote class. You should never have to
* call this yourself.
*
* @param {Object} message
*/
Account.prototype.notifyTx = function (message)
{
Account.prototype.notify =
Account.prototype.notifyTx = function(transaction) {
// Only trigger the event if the account object is actually
// subscribed - this prevents some weird phantom events from
// occurring.
if (this._subs) {
this.emit('transaction', message);
if (!this._subs) {
return;
}
this.emit('transaction', transaction);
var account = transaction.transaction.Account;
if (!account) {
return;
}
var isThisAccount = (account === this._account_id);
this.emit(isThisAccount ? 'transaction-outbound' : 'transaction-inbound', transaction);
};
/**
* Submit a transaction to an account's
* transaction manager
*
* @param {Transaction} transaction
*/
Account.prototype.submit = function(transaction) {
this._transactionManager.submit(transaction);
};
/**
* Check whether the given public key is valid for this account
*
* @param {Hex-encoded String|RippleAddress} public_key
* @param {Function} callback
*
* @callback
* @param {Error} err
* @param {Boolean} true if the public key is valid and active, false otherwise
*/
Account.prototype.publicKeyIsActive = function(public_key, callback) {
var self = this;
var public_key_as_uint160;
try {
public_key_as_uint160 = Account._publicKeyToAddress(public_key);
} catch (err) {
return callback(err);
}
function getAccountInfo(async_callback) {
self.getInfo(function(err, account_info_res){
// If the remote responds with an Account Not Found error then the account
// is unfunded and thus we can assume that the master key is active
if (err && err.remote && err.remote.error === 'actNotFound') {
async_callback(null, null);
} else {
async_callback(err, account_info_res);
}
});
};
function publicKeyIsValid(account_info_res, async_callback) {
// Catch the case of unfunded accounts
if (!account_info_res) {
if (public_key_as_uint160 === self._account_id) {
async_callback(null, true);
} else {
async_callback(null, false);
}
return;
}
var account_info = account_info_res.account_data;
// Respond with true if the RegularKey is set and matches the given public key or
// if the public key matches the account address and the lsfDisableMaster is not set
if (account_info.RegularKey &&
account_info.RegularKey === public_key_as_uint160) {
async_callback(null, true);
} else if (account_info.Account === public_key_as_uint160 &&
((account_info.Flags & 0x00100000) === 0)) {
async_callback(null, true);
} else {
async_callback(null, false);
}
};
var steps = [
getAccountInfo,
publicKeyIsValid
];
async.waterfall(steps, callback);
};
/**
* Convert a hex-encoded public key to a Ripple Address
*
* @static
*
* @param {Hex-encoded string|RippleAddress} public_key
* @returns {RippleAddress}
*/
Account._publicKeyToAddress = function(public_key) {
// Based on functions in /src/js/ripple/keypair.js
function hexToUInt160(public_key) {
var bits = sjcl.codec.hex.toBits(public_key);
var hash = sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
var address = UInt160.from_bits(hash);
address.set_version(Base.VER_ACCOUNT_ID);
return address.to_json();
};
if (UInt160.is_valid(public_key)) {
return public_key;
} else if (/^[0-9a-fA-F]+$/.test(public_key)) {
return hexToUInt160(public_key);
} else {
throw new Error('Public key is invalid. Must be a UInt160 or a hex string');
}
};
exports.Account = Account;
exports.Account = Account;
// vim:sw=2:sts=2:ts=8:et

File diff suppressed because it is too large Load Diff

59
src/js/ripple/authinfo.js Normal file
View File

@@ -0,0 +1,59 @@
var async = require('async');
var superagent = require('superagent');
var RippleTxt = require('./rippletxt').RippleTxt;
var AuthInfo = { };
AuthInfo._getRippleTxt = function(domain, callback) {
RippleTxt.get(domain, callback);
};
AuthInfo._getUser = function(url, callback) {
superagent.get(url, callback);
};
/**
* Get auth info for a given username
*
* @param {string} domain - Domain which hosts the user's info
* @param {string} username - Username who's info we are retreiving
* @param {function} fn - Callback function
*/
AuthInfo.get = function(domain, username, callback) {
var self = this;
username = username.toLowerCase();
function getRippleTxt(callback) {
self._getRippleTxt(domain, function(err, txt) {
if (err) {
return callback(err);
}
if (!txt.authinfo_url) {
return callback(new Error('Authentication is not supported on ' + domain));
}
var url = Array.isArray(txt.authinfo_url) ? txt.authinfo_url[0] : txt.authinfo_url;
url += '?domain=' + domain + '&username=' + username;
callback(null, url);
});
};
function getUser(url, callback) {
self._getUser(url, function(err, res) {
if (err || res.error) {
callback(new Error('Authentication info server unreachable'));
} else {
callback(null, res.body);
}
});
};
async.waterfall([ getRippleTxt, getUser ], callback);
};
exports.AuthInfo = AuthInfo;

View File

@@ -1,161 +1,169 @@
var sjcl = require('../../../build/sjcl');
var sjcl = require('./utils').sjcl;
var utils = require('./utils');
var jsbn = require('./jsbn');
var extend = require('extend');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var BigInteger = utils.jsbn.BigInteger;
var Base = {};
var alphabets = Base.alphabets = {
'ripple' : "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
'tipple' : "RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz",
'bitcoin' : "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var alphabets = Base.alphabets = {
ripple: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz',
tipple: 'RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz',
bitcoin: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
};
extend(Base, {
'VER_NONE' : 1,
'VER_NODE_PUBLIC' : 28,
'VER_NODE_PRIVATE' : 32,
'VER_ACCOUNT_ID' : 0,
'VER_ACCOUNT_PUBLIC' : 35,
'VER_ACCOUNT_PRIVATE' : 34,
'VER_FAMILY_GENERATOR' : 41,
'VER_FAMILY_SEED' : 33
VER_NONE : 1,
VER_NODE_PUBLIC : 28,
VER_NODE_PRIVATE : 32,
VER_ACCOUNT_ID : 0,
VER_ACCOUNT_PUBLIC : 35,
VER_ACCOUNT_PRIVATE : 34,
VER_FAMILY_GENERATOR : 41,
VER_FAMILY_SEED : 33
});
var sha256 = function (bytes) {
function sha256(bytes) {
return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
};
var sha256hash = function (bytes) {
function sha256hash(bytes) {
return sha256(sha256(bytes));
};
// --> input: big-endian array of bytes.
// <-- string at least as long as input.
Base.encode = function (input, alpha) {
var alphabet = alphabets[alpha || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_q = nbi();
var bi_r = nbi();
var bi_value = new BigInteger(input);
var buffer = [];
Base.encode = function(input, alpha) {
var alphabet = alphabets[alpha || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_q = new BigInteger();
var bi_r = new BigInteger();
var bi_value = new BigInteger(input);
var buffer = [];
while (bi_value.compareTo(BigInteger.ZERO) > 0)
{
while (bi_value.compareTo(BigInteger.ZERO) > 0) {
bi_value.divRemTo(bi_base, bi_q, bi_r);
bi_q.copyTo(bi_value);
buffer.push(alphabet[bi_r.intValue()]);
}
var i;
for (i = 0; i != input.length && !input[i]; i += 1) {
for (var i=0; i !== input.length && !input[i]; i += 1) {
buffer.push(alphabet[0]);
}
return buffer.reverse().join("");
return buffer.reverse().join('');
};
// --> input: String
// <-- array of bytes or undefined.
Base.decode = function (input, alpha) {
if ("string" !== typeof input) return undefined;
Base.decode = function(input, alpha) {
if (typeof input !== 'string') {
return void(0);
}
var alphabet = alphabets[alpha || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_value = nbi();
var alphabet = alphabets[alpha || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_value = new BigInteger();
var i;
for (i = 0; i != input.length && input[i] === alphabet[0]; i += 1)
;
for (i = 0; i !== input.length && input[i] === alphabet[0]; i += 1) {
}
for (; i != input.length; i += 1) {
var v = alphabet.indexOf(input[i]);
for (; i !== input.length; i += 1) {
var v = alphabet.indexOf(input[i]);
if (v < 0)
return undefined;
var r = nbi();
if (v < 0) {
return void(0);
}
var r = new BigInteger();
r.fromInt(v);
bi_value = bi_value.multiply(bi_base).add(r);
}
// toByteArray:
// - Returns leading zeros!
// - Returns signed bytes!
var bytes = bi_value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0; });
var bytes = bi_value.toByteArray().map(function(b) { return b ? b < 0 ? 256+b : b : 0; });
var extra = 0;
while (extra != bytes.length && !bytes[extra])
while (extra !== bytes.length && !bytes[extra]) {
extra += 1;
}
if (extra)
if (extra) {
bytes = bytes.slice(extra);
}
var zeros = 0;
while (zeros !== input.length && input[zeros] === alphabet[0])
while (zeros !== input.length && input[zeros] === alphabet[0]) {
zeros += 1;
}
return [].concat(utils.arraySet(zeros, 0), bytes);
};
Base.verify_checksum = function (bytes) {
var computed = sha256hash(bytes.slice(0, -4)).slice(0, 4);
var checksum = bytes.slice(-4);
Base.verify_checksum = function(bytes) {
var computed = sha256hash(bytes.slice(0, -4)).slice(0, 4);
var checksum = bytes.slice(-4);
var result = true;
for (var i = 0; i < 4; i++)
if (computed[i] !== checksum[i])
return false;
for (var i=0; i<4; i++) {
if (computed[i] !== checksum[i]) {
result = false;
break;
}
}
return true;
return result;
};
// --> input: Array
// <-- String
Base.encode_check = function (version, input, alphabet) {
var buffer = [].concat(version, input);
var check = sha256(sha256(buffer)).slice(0, 4);
Base.encode_check = function(version, input, alphabet) {
var buffer = [].concat(version, input);
var check = sha256(sha256(buffer)).slice(0, 4);
return Base.encode([].concat(buffer, check), alphabet);
}
};
// --> input : String
// <-- NaN || BigInteger
Base.decode_check = function (version, input, alphabet) {
Base.decode_check = function(version, input, alphabet) {
var buffer = Base.decode(input, alphabet);
if (!buffer || buffer.length < 5)
if (!buffer || buffer.length < 5) {
return NaN;
// Single valid version
if ("number" === typeof version && buffer[0] !== version)
return NaN;
// Multiple allowed versions
if ("object" === typeof version && Array.isArray(version)) {
var match = false;
for (var i = 0, l = version.length; i < l; i++) {
match |= version[i] === buffer[0];
}
if (!match) return NaN;
}
if (!Base.verify_checksum(buffer))
// Single valid version
if (typeof version === 'number' && buffer[0] !== version) {
return NaN;
}
// Multiple allowed versions
if (Array.isArray(version)) {
var match = false;
for (var i=0, l=version.length; i<l; i++) {
match |= version[i] === buffer[0];
}
if (!match) {
return NaN;
}
}
if (!Base.verify_checksum(buffer)) {
return NaN;
}
// We'll use the version byte to add a leading zero, this ensures JSBN doesn't
// intrepret the value as a negative number
buffer[0] = 0;
return new BigInteger(buffer.slice(0, -4), 256);
}
};
exports.Base = Base;

View File

@@ -1,90 +1,404 @@
var ST = require("./serializedtypes");
/**
* Data type map.
*
* Mapping of type ids to data types. The type id is specified by the high
*/
var TYPES_MAP = exports.types = [
void(0),
// Common
'Int16', // 1
'Int32', // 2
'Int64', // 3
'Hash128', // 4
'Hash256', // 5
'Amount', // 6
'VL', // 7
'Account', // 8
// 9-13 reserved
void(0), // 9
void(0), // 10
void(0), // 11
void(0), // 12
void(0), // 13
'Object', // 14
'Array', // 15
// Uncommon
'Int8', // 16
'Hash160', // 17
'PathSet', // 18
'Vector256' // 19
];
/**
* Field type map.
*
* Mapping of field type id to field type name.
*/
var FIELDS_MAP = exports.fields = {
// Common types
1: { // Int16
1: 'LedgerEntryType',
2: 'TransactionType'
},
2: { // Int32
2: 'Flags',
3: 'SourceTag',
4: 'Sequence',
5: 'PreviousTxnLgrSeq',
6: 'LedgerSequence',
7: 'CloseTime',
8: 'ParentCloseTime',
9: 'SigningTime',
10: 'Expiration',
11: 'TransferRate',
12: 'WalletSize',
13: 'OwnerCount',
14: 'DestinationTag',
// Skip 15
16: 'HighQualityIn',
17: 'HighQualityOut',
18: 'LowQualityIn',
19: 'LowQualityOut',
20: 'QualityIn',
21: 'QualityOut',
22: 'StampEscrow',
23: 'BondAmount',
24: 'LoadFee',
25: 'OfferSequence',
26: 'FirstLedgerSequence',
27: 'LastLedgerSequence',
28: 'TransactionIndex',
29: 'OperationLimit',
30: 'ReferenceFeeUnits',
31: 'ReserveBase',
32: 'ReserveIncrement',
33: 'SetFlag',
34: 'ClearFlag'
},
3: { // Int64
1: 'IndexNext',
2: 'IndexPrevious',
3: 'BookNode',
4: 'OwnerNode',
5: 'BaseFee',
6: 'ExchangeRate',
7: 'LowNode',
8: 'HighNode'
},
4: { // Hash128
1: 'EmailHash'
},
5: { // Hash256
1: 'LedgerHash',
2: 'ParentHash',
3: 'TransactionHash',
4: 'AccountHash',
5: 'PreviousTxnID',
6: 'LedgerIndex',
7: 'WalletLocator',
8: 'RootIndex',
9: 'AccountTxnID',
16: 'BookDirectory',
17: 'InvoiceID',
18: 'Nickname',
19: 'Feature'
},
6: { // Amount
1: 'Amount',
2: 'Balance',
3: 'LimitAmount',
4: 'TakerPays',
5: 'TakerGets',
6: 'LowLimit',
7: 'HighLimit',
8: 'Fee',
9: 'SendMax',
16: 'MinimumOffer',
17: 'RippleEscrow',
18: 'DeliveredAmount'
},
7: { // VL
1: 'PublicKey',
2: 'MessageKey',
3: 'SigningPubKey',
4: 'TxnSignature',
5: 'Generator',
6: 'Signature',
7: 'Domain',
8: 'FundCode',
9: 'RemoveCode',
10: 'ExpireCode',
11: 'CreateCode',
12: 'MemoType',
13: 'MemoData'
},
8: { // Account
1: 'Account',
2: 'Owner',
3: 'Destination',
4: 'Issuer',
7: 'Target',
8: 'RegularKey'
},
14: { // Object
1: void(0), //end of Object
2: 'TransactionMetaData',
3: 'CreatedNode',
4: 'DeletedNode',
5: 'ModifiedNode',
6: 'PreviousFields',
7: 'FinalFields',
8: 'NewFields',
9: 'TemplateEntry',
10: 'Memo'
},
15: { // Array
1: void(0), //end of Array
2: 'SigningAccounts',
3: 'TxnSignatures',
4: 'Signatures',
5: 'Template',
6: 'Necessary',
7: 'Sufficient',
8: 'AffectedNodes',
9: 'Memos'
},
// Uncommon types
16: { // Int8
1: 'CloseResolution',
2: 'TemplateEntryType',
3: 'TransactionResult'
},
17: { // Hash160
1: 'TakerPaysCurrency',
2: 'TakerPaysIssuer',
3: 'TakerGetsCurrency',
4: 'TakerGetsIssuer'
},
18: { // PathSet
1: 'Paths'
},
19: { // Vector256
1: 'Indexes',
2: 'Hashes',
3: 'Features'
}
};
var INVERSE_FIELDS_MAP = exports.fieldsInverseMap = { };
Object.keys(FIELDS_MAP).forEach(function(k1) {
Object.keys(FIELDS_MAP[k1]).forEach(function(k2) {
INVERSE_FIELDS_MAP[FIELDS_MAP[k1][k2]] = [ Number(k1), Number(k2) ];
});
});
var REQUIRED = exports.REQUIRED = 0,
OPTIONAL = exports.OPTIONAL = 1,
DEFAULT = exports.DEFAULT = 2;
ST.Int16.id = 1;
ST.Int32.id = 2;
ST.Int64.id = 3;
ST.Hash128.id = 4;
ST.Hash256.id = 5;
ST.Amount.id = 6;
ST.VariableLength.id = 7;
ST.Account.id = 8;
ST.Object.id = 14;
ST.Array.id = 15;
ST.Int8.id = 16;
ST.Hash160.id = 17;
ST.PathSet.id = 18;
ST.Vector256.id = 19;
var base = [
[ 'TransactionType' , REQUIRED, 2, ST.Int16 ],
[ 'Flags' , OPTIONAL, 2, ST.Int32 ],
[ 'SourceTag' , OPTIONAL, 3, ST.Int32 ],
[ 'Account' , REQUIRED, 1, ST.Account ],
[ 'Sequence' , REQUIRED, 4, ST.Int32 ],
[ 'Fee' , REQUIRED, 8, ST.Amount ],
[ 'OperationLimit' , OPTIONAL, 29, ST.Int32 ],
[ 'SigningPubKey' , REQUIRED, 3, ST.VariableLength ],
[ 'TxnSignature' , OPTIONAL, 4, ST.VariableLength ]
[ 'TransactionType' , REQUIRED ],
[ 'Flags' , OPTIONAL ],
[ 'SourceTag' , OPTIONAL ],
[ 'LastLedgerSequence' , OPTIONAL ],
[ 'Account' , REQUIRED ],
[ 'Sequence' , REQUIRED ],
[ 'Fee' , REQUIRED ],
[ 'OperationLimit' , OPTIONAL ],
[ 'SigningPubKey' , REQUIRED ],
[ 'TxnSignature' , OPTIONAL ]
];
exports.tx = {
AccountSet: [3].concat(base, [
[ 'EmailHash' , OPTIONAL, 1, ST.Hash128 ],
[ 'WalletLocator' , OPTIONAL, 7, ST.Hash256 ],
[ 'WalletSize' , OPTIONAL, 12, ST.Int32 ],
[ 'MessageKey' , OPTIONAL, 2, ST.VariableLength ],
[ 'Domain' , OPTIONAL, 7, ST.VariableLength ],
[ 'TransferRate' , OPTIONAL, 11, ST.Int32 ]
[ 'EmailHash' , OPTIONAL ],
[ 'WalletLocator' , OPTIONAL ],
[ 'WalletSize' , OPTIONAL ],
[ 'MessageKey' , OPTIONAL ],
[ 'Domain' , OPTIONAL ],
[ 'TransferRate' , OPTIONAL ]
]),
TrustSet: [20].concat(base, [
[ 'LimitAmount' , OPTIONAL, 3, ST.Amount ],
[ 'QualityIn' , OPTIONAL, 20, ST.Int32 ],
[ 'QualityOut' , OPTIONAL, 21, ST.Int32 ]
[ 'LimitAmount' , OPTIONAL ],
[ 'QualityIn' , OPTIONAL ],
[ 'QualityOut' , OPTIONAL ]
]),
OfferCreate: [7].concat(base, [
[ 'TakerPays' , REQUIRED, 4, ST.Amount ],
[ 'TakerGets' , REQUIRED, 5, ST.Amount ],
[ 'Expiration' , OPTIONAL, 10, ST.Int32 ]
[ 'TakerPays' , REQUIRED ],
[ 'TakerGets' , REQUIRED ],
[ 'Expiration' , OPTIONAL ]
]),
OfferCancel: [8].concat(base, [
[ 'OfferSequence' , REQUIRED, 25, ST.Int32 ]
[ 'OfferSequence' , REQUIRED ]
]),
SetRegularKey: [5].concat(base, [
[ 'RegularKey' , REQUIRED, 8, ST.Account ]
[ 'RegularKey' , REQUIRED ]
]),
Payment: [0].concat(base, [
[ 'Destination' , REQUIRED, 3, ST.Account ],
[ 'Amount' , REQUIRED, 1, ST.Amount ],
[ 'SendMax' , OPTIONAL, 9, ST.Amount ],
[ 'Paths' , DEFAULT , 1, ST.PathSet ],
[ 'InvoiceID' , OPTIONAL, 17, ST.Hash256 ],
[ 'DestinationTag' , OPTIONAL, 14, ST.Int32 ]
[ 'Destination' , REQUIRED ],
[ 'Amount' , REQUIRED ],
[ 'SendMax' , OPTIONAL ],
[ 'Paths' , DEFAULT ],
[ 'InvoiceID' , OPTIONAL ],
[ 'DestinationTag' , OPTIONAL ]
]),
Contract: [9].concat(base, [
[ 'Expiration' , REQUIRED, 10, ST.Int32 ],
[ 'BondAmount' , REQUIRED, 23, ST.Int32 ],
[ 'StampEscrow' , REQUIRED, 22, ST.Int32 ],
[ 'RippleEscrow' , REQUIRED, 17, ST.Amount ],
[ 'CreateCode' , OPTIONAL, 11, ST.VariableLength ],
[ 'FundCode' , OPTIONAL, 8, ST.VariableLength ],
[ 'RemoveCode' , OPTIONAL, 9, ST.VariableLength ],
[ 'ExpireCode' , OPTIONAL, 10, ST.VariableLength ]
[ 'Expiration' , REQUIRED ],
[ 'BondAmount' , REQUIRED ],
[ 'StampEscrow' , REQUIRED ],
[ 'RippleEscrow' , REQUIRED ],
[ 'CreateCode' , OPTIONAL ],
[ 'FundCode' , OPTIONAL ],
[ 'RemoveCode' , OPTIONAL ],
[ 'ExpireCode' , OPTIONAL ]
]),
RemoveContract: [10].concat(base, [
[ 'Target' , REQUIRED, 7, ST.Account ]
[ 'Target' , REQUIRED ]
]),
EnableFeature: [100].concat(base, [
[ 'Feature' , REQUIRED, 19, ST.Hash256 ]
[ 'Feature' , REQUIRED ]
]),
SetFee: [101].concat(base, [
[ 'Features' , REQUIRED, 9, ST.Array ],
[ 'BaseFee' , REQUIRED, 5, ST.Int64 ],
[ 'ReferenceFeeUnits' , REQUIRED, 30, ST.Int32 ],
[ 'ReserveBase' , REQUIRED, 31, ST.Int32 ],
[ 'ReserveIncrement' , REQUIRED, 32, ST.Int32 ]
[ 'Features' , REQUIRED ],
[ 'BaseFee' , REQUIRED ],
[ 'ReferenceFeeUnits' , REQUIRED ],
[ 'ReserveBase' , REQUIRED ],
[ 'ReserveIncrement' , REQUIRED ]
])
};
var sleBase = [
['LedgerIndex', OPTIONAL],
['LedgerEntryType', REQUIRED],
['Flags', REQUIRED]
];
exports.ledger = {
AccountRoot: [97].concat(sleBase,[
['Sequence', REQUIRED],
['PreviousTxnLgrSeq', REQUIRED],
['TransferRate', OPTIONAL],
['WalletSize', OPTIONAL],
['OwnerCount', REQUIRED],
['EmailHash', OPTIONAL],
['PreviousTxnID', REQUIRED],
['AccountTxnID', OPTIONAL],
['WalletLocator', OPTIONAL],
['Balance', REQUIRED],
['MessageKey', OPTIONAL],
['Domain', OPTIONAL],
['Account', REQUIRED],
['RegularKey', OPTIONAL]]),
Contract: [99].concat(sleBase,[
['PreviousTxnLgrSeq', REQUIRED],
['Expiration', REQUIRED],
['BondAmount', REQUIRED],
['PreviousTxnID', REQUIRED],
['Balance', REQUIRED],
['FundCode', OPTIONAL],
['RemoveCode', OPTIONAL],
['ExpireCode', OPTIONAL],
['CreateCode', OPTIONAL],
['Account', REQUIRED],
['Owner', REQUIRED],
['Issuer', REQUIRED]]),
DirectoryNode: [100].concat(sleBase,[
['IndexNext', OPTIONAL],
['IndexPrevious', OPTIONAL],
['ExchangeRate', OPTIONAL],
['RootIndex', REQUIRED],
['Owner', OPTIONAL],
['TakerPaysCurrency', OPTIONAL],
['TakerPaysIssuer', OPTIONAL],
['TakerGetsCurrency', OPTIONAL],
['TakerGetsIssuer', OPTIONAL],
['Indexes', REQUIRED]]),
EnabledFeatures: [102].concat(sleBase,[
['Features', REQUIRED]]),
FeeSettings: [115].concat(sleBase,[
['ReferenceFeeUnits', REQUIRED],
['ReserveBase', REQUIRED],
['ReserveIncrement', REQUIRED],
['BaseFee', REQUIRED],
['LedgerIndex', OPTIONAL]]),
GeneratorMap: [103].concat(sleBase,[
['Generator', REQUIRED]]),
LedgerHashes: [104].concat(sleBase,[
['LedgerEntryType', REQUIRED],
['Flags', REQUIRED],
['FirstLedgerSequence', OPTIONAL],
['LastLedgerSequence', OPTIONAL],
['LedgerIndex', OPTIONAL],
['Hashes', REQUIRED]]),
Nickname: [110].concat(sleBase,[
['LedgerEntryType', REQUIRED],
['Flags', REQUIRED],
['LedgerIndex', OPTIONAL],
['MinimumOffer', OPTIONAL],
['Account', REQUIRED]]),
Offer: [111].concat(sleBase,[
['LedgerEntryType', REQUIRED],
['Flags', REQUIRED],
['Sequence', REQUIRED],
['PreviousTxnLgrSeq', REQUIRED],
['Expiration', OPTIONAL],
['BookNode', REQUIRED],
['OwnerNode', REQUIRED],
['PreviousTxnID', REQUIRED],
['LedgerIndex', OPTIONAL],
['BookDirectory', REQUIRED],
['TakerPays', REQUIRED],
['TakerGets', REQUIRED],
['Account', REQUIRED]]),
RippleState: [114].concat(sleBase,[
['LedgerEntryType', REQUIRED],
['Flags', REQUIRED],
['PreviousTxnLgrSeq', REQUIRED],
['HighQualityIn', OPTIONAL],
['HighQualityOut', OPTIONAL],
['LowQualityIn', OPTIONAL],
['LowQualityOut', OPTIONAL],
['LowNode', OPTIONAL],
['HighNode', OPTIONAL],
['PreviousTxnID', REQUIRED],
['LedgerIndex', OPTIONAL],
['Balance', REQUIRED],
['LowLimit', REQUIRED],
['HighLimit', REQUIRED]])
}
exports.metadata = [
[ 'TransactionIndex' , REQUIRED ],
[ 'TransactionResult' , REQUIRED ],
[ 'AffectedNodes' , REQUIRED ]
];
exports.ter = {
tesSUCCESS: 0,
tecCLAIM: 100,
tecPATH_PARTIAL: 101,
tecUNFUNDED_ADD: 102,
tecUNFUNDED_OFFER: 103,
tecUNFUNDED_PAYMENT: 104,
tecFAILED_PROCESSING: 105,
tecDIR_FULL: 121,
tecINSUF_RESERVE_LINE: 122,
tecINSUF_RESERVE_OFFER: 123,
tecNO_DST: 124,
tecNO_DST_INSUF_XRP: 125,
tecNO_LINE_INSUF_RESERVE: 126,
tecNO_LINE_REDUNDANT: 127,
tecPATH_DRY: 128,
tecUNFUNDED: 129,
tecMASTER_DISABLED: 130,
tecNO_REGULAR_KEY: 131,
tecOWNERS: 132
};

1174
src/js/ripple/blob.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
// This object serves as a singleton to store config options
var extend = require("extend");
var extend = require('extend');
var config = module.exports = {
load: function (newOpts) {

313
src/js/ripple/crypt.js Normal file
View File

@@ -0,0 +1,313 @@
var sjcl = require('./utils').sjcl;
var base = require('./base').Base;
var Seed = require('./seed').Seed;
var UInt160 = require('./uint160').UInt160;
var UInt256 = require('./uint256').UInt256;
var request = require('superagent');
var querystring = require('querystring');
var extend = require("extend");
var parser = require("url");
var Crypt = { };
var cryptConfig = {
cipher : 'aes',
mode : 'ccm',
ts : 64, // tag length
ks : 256, // key size
iter : 1000 // iterations (key derivation)
};
/**
* Full domain hash based on SHA512
*/
function fdh(data, bytelen) {
var bitlen = bytelen << 3;
if (typeof data === 'string') {
data = sjcl.codec.utf8String.toBits(data);
}
// Add hashing rounds until we exceed desired length in bits
var counter = 0, output = [];
while (sjcl.bitArray.bitLength(output) < bitlen) {
var hash = sjcl.hash.sha512.hash(sjcl.bitArray.concat([counter], data));
output = sjcl.bitArray.concat(output, hash);
counter++;
}
// Truncate to desired length
output = sjcl.bitArray.clamp(output, bitlen);
return output;
};
/**
* This is a function to derive different hashes from the same key.
* Each hash is derived as HMAC-SHA512HALF(key, token).
*
* @param {string} key
* @param {string} hash
*/
function keyHash(key, token) {
var hmac = new sjcl.misc.hmac(key, sjcl.hash.sha512);
return sjcl.codec.hex.fromBits(sjcl.bitArray.bitSlice(hmac.encrypt(token), 0, 256));
};
/****** exposed functions ******/
/**
* KEY DERIVATION FUNCTION
*
* This service takes care of the key derivation, i.e. converting low-entropy
* secret into higher entropy secret via either computationally expensive
* processes or peer-assisted key derivation (PAKDF).
*
* @param {object} opts
* @param {string} purpose - Key type/purpose
* @param {string} username
* @param {string} secret - Also known as passphrase/password
* @param {function} fn
*/
Crypt.derive = function(opts, purpose, username, secret, fn) {
var tokens;
if (purpose === 'login') {
tokens = ['id', 'crypt'];
} else {
tokens = ['unlock'];
}
var iExponent = new sjcl.bn(String(opts.exponent));
var iModulus = new sjcl.bn(String(opts.modulus));
var iAlpha = new sjcl.bn(String(opts.alpha));
var publicInfo = [ 'PAKDF_1_0_0', opts.host.length, opts.host, username.length, username, purpose.length, purpose ].join(':') + ':';
var publicSize = Math.ceil(Math.min((7 + iModulus.bitLength()) >>> 3, 256) / 8);
var publicHash = fdh(publicInfo, publicSize);
var publicHex = sjcl.codec.hex.fromBits(publicHash);
var iPublic = new sjcl.bn(String(publicHex)).setBitM(0);
var secretInfo = [ publicInfo, secret.length, secret ].join(':') + ':';
var secretSize = (7 + iModulus.bitLength()) >>> 3;
var secretHash = fdh(secretInfo, secretSize);
var secretHex = sjcl.codec.hex.fromBits(secretHash);
var iSecret = new sjcl.bn(String(secretHex)).mod(iModulus);
if (iSecret.jacobi(iModulus) !== 1) {
iSecret = iSecret.mul(iAlpha).mod(iModulus);
}
var iRandom;
for (;;) {
iRandom = sjcl.bn.random(iModulus, 0);
if (iRandom.jacobi(iModulus) === 1) {
break;
}
}
var iBlind = iRandom.powermodMontgomery(iPublic.mul(iExponent), iModulus);
var iSignreq = iSecret.mulmod(iBlind, iModulus);
var signreq = sjcl.codec.hex.fromBits(iSignreq.toBits());
request.post(opts.url)
.send({ info: publicInfo, signreq: signreq })
.end(function(err, resp) {
if (err || !resp) {
return fn(new Error('Could not query PAKDF server ' + opts.host));
}
var data = resp.body || resp.text ? JSON.parse(resp.text) : {};
if (data.result !== 'success') {
return fn(new Error('Could not query PAKDF server '+opts.host));
}
var iSignres = new sjcl.bn(String(data.signres));
var iRandomInv = iRandom.inverseMod(iModulus);
var iSigned = iSignres.mulmod(iRandomInv, iModulus);
var key = iSigned.toBits();
var result = { };
tokens.forEach(function(token) {
result[token] = keyHash(key, token);
});
fn(null, result);
});
};
/**
* Imported from ripple-client
*/
/**
* Encrypt data
*
* @param {string} key
* @param {string} data
*/
Crypt.encrypt = function(key, data) {
key = sjcl.codec.hex.toBits(key);
var opts = extend(true, {}, cryptConfig);
var encryptedObj = JSON.parse(sjcl.encrypt(key, data, opts));
var version = [sjcl.bitArray.partial(8, 0)];
var initVector = sjcl.codec.base64.toBits(encryptedObj.iv);
var ciphertext = sjcl.codec.base64.toBits(encryptedObj.ct);
var encryptedBits = sjcl.bitArray.concat(version, initVector);
encryptedBits = sjcl.bitArray.concat(encryptedBits, ciphertext);
return sjcl.codec.base64.fromBits(encryptedBits);
};
/**
* Decrypt data
*
* @param {string} key
* @param {string} data
*/
Crypt.decrypt = function (key, data) {
key = sjcl.codec.hex.toBits(key);
var encryptedBits = sjcl.codec.base64.toBits(data);
var version = sjcl.bitArray.extract(encryptedBits, 0, 8);
if (version !== 0) {
throw new Error('Unsupported encryption version: '+version);
}
var encrypted = extend(true, {}, cryptConfig, {
iv: sjcl.codec.base64.fromBits(sjcl.bitArray.bitSlice(encryptedBits, 8, 8+128)),
ct: sjcl.codec.base64.fromBits(sjcl.bitArray.bitSlice(encryptedBits, 8+128))
});
return sjcl.decrypt(key, JSON.stringify(encrypted));
};
/**
* Validate a ripple address
*
* @param {string} address
*/
Crypt.isValidAddress = function (address) {
return UInt160.is_valid(address);
};
/**
* Create an encryption key
*
* @param {integer} nWords - number of words
*/
Crypt.createSecret = function (nWords) {
return sjcl.codec.hex.fromBits(sjcl.random.randomWords(nWords));
};
/**
* Create a new master key
*/
Crypt.createMaster = function () {
return base.encode_check(33, sjcl.codec.bytes.fromBits(sjcl.random.randomWords(4)));
};
/**
* Create a ripple address from a master key
*
* @param {string} masterkey
*/
Crypt.getAddress = function (masterkey) {
return Seed.from_json(masterkey).get_key().get_address().to_json();
};
/**
* Hash data using SHA-512.
*
* @param {string|bitArray} data
* @return {string} Hash of the data
*/
Crypt.hashSha512 = function (data) {
// XXX Should return a UInt512
return sjcl.codec.hex.fromBits(sjcl.hash.sha512.hash(data));
};
/**
* Hash data using SHA-512 and return the first 256 bits.
*
* @param {string|bitArray} data
* @return {UInt256} Hash of the data
*/
Crypt.hashSha512Half = function (data) {
return UInt256.from_hex(Crypt.hashSha512(data).substr(0, 64));
};
/**
* Sign a data string with a secret key
*
* @param {string} secret
* @param {string} data
*/
Crypt.signString = function(secret, data) {
var hmac = new sjcl.misc.hmac(sjcl.codec.hex.toBits(secret), sjcl.hash.sha512);
return sjcl.codec.hex.fromBits(hmac.mac(data));
};
/**
* Create an an accout recovery key
*
* @param {string} secret
*/
Crypt.deriveRecoveryEncryptionKeyFromSecret = function(secret) {
var seed = Seed.from_json(secret).to_bits();
var hmac = new sjcl.misc.hmac(seed, sjcl.hash.sha512);
var key = hmac.mac('ripple/hmac/recovery_encryption_key/v1');
key = sjcl.bitArray.bitSlice(key, 0, 256);
return sjcl.codec.hex.fromBits(key);
};
/**
* Convert base64 encoded data into base64url encoded data.
*
* @param {String} base64 Data
*/
Crypt.base64ToBase64Url = function(encodedData) {
return encodedData.replace(/\+/g, '-').replace(/\//g, '_').replace(/[=]+$/, '');
};
/**
* Convert base64url encoded data into base64 encoded data.
*
* @param {String} base64 Data
*/
Crypt.base64UrlToBase64 = function(encodedData) {
encodedData = encodedData.replace(/-/g, '+').replace(/_/g, '/');
while (encodedData.length % 4) {
encodedData += '=';
}
return encodedData;
};
exports.Crypt = Crypt;

View File

@@ -1,10 +1,13 @@
var extend = require('extend');
var UInt160 = require('./uint160').UInt160;
var utils = require('./utils');
var Float = require('./ieee754').Float;
//
// Currency support
//
// XXX Internal form should be UInt160.
var Currency = function () {
var Currency = extend(function() {
// Internal form: 0 = XRP. 3 letter-code.
// XXX Internal should be 0 or hex with three letter annotation when valid.
@@ -14,72 +17,337 @@ var Currency = function () {
// XXX Should support hex, C++ doesn't currently allow it.
this._value = NaN;
this._update();
}, UInt160);
Currency.prototype = extend({}, UInt160.prototype);
Currency.prototype.constructor = Currency;
Currency.HEX_CURRENCY_BAD = '0000000000000000000000005852500000000000';
/**
* Tries to correctly interpret a Currency as entered by a user.
*
* Examples:
*
* USD => currency
* USD - Dollar => currency with optional full currency name
* XAU (-0.5%pa) => XAU with 0.5% effective demurrage rate per year
* XAU - Gold (-0.5%pa) => Optionally allowed full currency name
* USD (1%pa) => US dollars with 1% effective interest per year
* INR - Indian Rupees => Optional full currency name with spaces
* TYX - 30-Year Treasuries => Optional full currency with numbers and a dash
* TYX - 30-Year Treasuries (1.5%pa) => Optional full currency with numbers, dash and interest rate
*
* The regular expression below matches above cases, broken down for better understanding:
*
* ^\s* // start with any amount of whitespace
* ([a-zA-Z]{3}|[0-9]{3}) // either 3 letter alphabetic currency-code or 3 digit numeric currency-code. See ISO 4217
* (\s*-\s*[- \w]+) // optional full currency name following the dash after currency code,
* full currency code can contain letters, numbers and dashes
* (\s*\(-?\d+\.?\d*%pa\))? // optional demurrage rate, has optional - and . notation (-0.5%pa)
* \s*$ // end with any amount of whitespace
*
*/
Currency.prototype.human_RE = /^\s*([a-zA-Z]{3}|[0-9]{3})(\s*-\s*[- \w]+)?(\s*\(-?\d+\.?\d*%pa\))?\s*$/;
Currency.from_json = function(j, shouldInterpretXrpAsIou) {
if (j instanceof this) {
return j.clone();
} else {
return (new this()).parse_json(j, shouldInterpretXrpAsIou);
}
};
Currency.from_human = function(j, opts) {
return (new Currency().parse_human(j, opts));
}
// Given "USD" return the json.
Currency.json_rewrite = function (j) {
return Currency.from_json(j).to_json();
};
Currency.from_json = function (j) {
if (j instanceof Currency) return j.clone();
else if ('string' === typeof j || 'number' === typeof j) return (new Currency()).parse_json(j);
else return new Currency(); // NaN
};
Currency.is_valid = function (j) {
return Currency.from_json(j).is_valid();
};
Currency.prototype.clone = function() {
return this.copyTo(new Currency());
};
// Returns copy.
Currency.prototype.copyTo = function (d) {
d._value = this._value;
return d;
};
Currency.prototype.equals = function (d) {
return ('string' !== typeof this._value && isNaN(this._value))
|| ('string' !== typeof d._value && isNaN(d._value)) ? false : this._value === d._value;
};
// this._value = NaN on error.
Currency.prototype.parse_json = function (j) {
if ("" === j || "0" === j || "XRP" === j) {
this._value = 0;
}
else if ('number' === typeof j) {
// XXX This is a hack
this._value = j;
}
else if ('string' != typeof j || 3 !== j.length) {
this._value = NaN;
}
else {
this._value = j;
Currency.prototype.parse_json = function(j, shouldInterpretXrpAsIou) {
this._value = NaN;
switch (typeof j) {
case 'string':
if (!j || /^(0|XRP)$/.test(j)) {
if (shouldInterpretXrpAsIou) {
this.parse_hex(Currency.HEX_CURRENCY_BAD);
} else {
this.parse_hex(Currency.HEX_ZERO);
}
break;
}
// match the given string to see if it's in an allowed format
var matches = String(j).match(this.human_RE);
if (matches) {
var currencyCode = matches[1];
// the full currency is matched as it is part of the valid currency format, but not stored
// var full_currency = matches[2] || '';
var interest = matches[3] || '';
// interest is defined as interest per year, per annum (pa)
var percentage = interest.match(/(-?\d+\.?\d+)/);
currencyCode = currencyCode.toUpperCase();
var currencyData = utils.arraySet(20, 0);
if (percentage) {
/*
* 20 byte layout of a interest bearing currency
*
* 01 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
* CURCODE- DATE------- RATE------------------- RESERVED---
*/
// byte 1 for type, use '1' to denote demurrage currency
currencyData[0] = 1;
// byte 2-4 for currency code
currencyData[1] = currencyCode.charCodeAt(0) & 0xff;
currencyData[2] = currencyCode.charCodeAt(1) & 0xff;
currencyData[3] = currencyCode.charCodeAt(2) & 0xff;
// byte 5-8 are for reference date, but should always be 0 so we won't fill it
// byte 9-16 are for the interest
percentage = parseFloat(percentage[0]);
// the interest or demurrage is expressed as a yearly (per annum) value
var secondsPerYear = 31536000; // 60 * 60 * 24 * 365
// Calculating the interest e-fold
// 0.5% demurrage is expressed 0.995, 0.005 less than 1
// 0.5% interest is expressed as 1.005, 0.005 more than 1
var interestEfold = secondsPerYear / Math.log(1 + percentage/100);
var bytes = Float.toIEEE754Double(interestEfold);
for (var i=0; i<=bytes.length; i++) {
currencyData[8 + i] = bytes[i] & 0xff;
}
// the last 4 bytes are reserved for future use, so we won't fill those
} else {
currencyData[12] = currencyCode.charCodeAt(0) & 0xff;
currencyData[13] = currencyCode.charCodeAt(1) & 0xff;
currencyData[14] = currencyCode.charCodeAt(2) & 0xff;
}
this.parse_bytes(currencyData);
} else {
this.parse_hex(j);
}
break;
case 'number':
if (!isNaN(j)) {
this.parse_number(j);
}
break;
case 'object':
if (j instanceof Currency) {
this._value = j.copyTo({})._value;
this._update();
}
break;
}
return this;
};
Currency.prototype.is_native = function () {
return !isNaN(this._value) && !this._value;
Currency.prototype.parse_human = function(j) {
return this.parse_json(j);
};
Currency.prototype.is_valid = function () {
return 'string' === typeof this._value || !isNaN(this._value);
/**
* Recalculate internal representation.
*
* You should never need to call this.
*/
Currency.prototype._update = function() {
var bytes = this.to_bytes();
// is it 0 everywhere except 12, 13, 14?
var isZeroExceptInStandardPositions = true;
if (!bytes) {
return 'XRP';
}
this._native = false;
this._type = -1;
this._interest_start = NaN;
this._interest_period = NaN;
this._iso_code = '';
for (var i=0; i<20; i++) {
isZeroExceptInStandardPositions = isZeroExceptInStandardPositions && (i===12 || i===13 || i===14 || bytes[i]===0);
}
if (isZeroExceptInStandardPositions) {
this._iso_code = String.fromCharCode(bytes[12])
+ String.fromCharCode(bytes[13])
+ String.fromCharCode(bytes[14]);
if (this._iso_code === '\0\0\0') {
this._native = true;
this._iso_code = 'XRP';
}
this._type = 0;
} else if (bytes[0] === 0x01) { // Demurrage currency
this._iso_code = String.fromCharCode(bytes[1])
+ String.fromCharCode(bytes[2])
+ String.fromCharCode(bytes[3]);
this._type = 1;
this._interest_start = (bytes[4] << 24) +
(bytes[5] << 16) +
(bytes[6] << 8) +
(bytes[7] );
this._interest_period = Float.fromIEEE754Double(bytes.slice(8, 16));
}
};
Currency.prototype.to_json = function () {
return this._value ? this._value : "XRP";
// XXX Probably not needed anymore?
/*
Currency.prototype.parse_bytes = function(byte_array) {
if (Array.isArray(byte_array) && byte_array.length === 20) {
var result;
// is it 0 everywhere except 12, 13, 14?
var isZeroExceptInStandardPositions = true;
for (var i=0; i<20; i++) {
isZeroExceptInStandardPositions = isZeroExceptInStandardPositions && (i===12 || i===13 || i===14 || byte_array[0]===0)
}
if (isZeroExceptInStandardPositions) {
var currencyCode = String.fromCharCode(byte_array[12])
+ String.fromCharCode(byte_array[13])
+ String.fromCharCode(byte_array[14]);
if (/^[A-Z0-9]{3}$/.test(currencyCode) && currencyCode !== 'XRP' ) {
this._value = currencyCode;
} else if (currencyCode === '\0\0\0') {
this._value = 0;
} else {
this._value = NaN;
}
} else {
// XXX Should support non-standard currency codes
this._value = NaN;
}
} else {
this._value = NaN;
}
return this;
};
*/
Currency.prototype.is_native = function() {
return this._native;
};
Currency.prototype.to_human = function () {
return this._value ? this._value : "XRP";
/**
* Whether this currency is an interest-bearing/demurring currency.
*/
Currency.prototype.has_interest = function() {
return this._type === 1 && !isNaN(this._interest_start) && !isNaN(this._interest_period);
};
/**
*
* @param referenceDate - number of seconds since the Ripple Epoch (0:00 on January 1, 2000 UTC)
* used to calculate the interest over provided interval
* pass in one years worth of seconds to ge the yearly interest
* @returns {number} - interest for provided interval, can be negative for demurred currencies
*/
Currency.prototype.get_interest_at = function(referenceDate, decimals) {
if (!this.has_interest) {
return 0;
}
// use one year as a default period
if (!referenceDate) {
referenceDate = this._interest_start + 3600 * 24 * 365;
}
if (referenceDate instanceof Date) {
referenceDate = utils.fromTimestamp(referenceDate.getTime());
}
// calculate interest by e-fold number
return Math.exp((referenceDate - this._interest_start) / this._interest_period);
};
Currency.prototype.get_interest_percentage_at = function(referenceDate, decimals) {
var interest = this.get_interest_at(referenceDate, decimals);
// convert to percentage
var interest = (interest*100)-100;
var decimalMultiplier = decimals ? Math.pow(10,decimals) : 100;
// round to two decimals behind the dot
return Math.round(interest*decimalMultiplier) / decimalMultiplier;
};
// XXX Currently we inherit UInt.prototype.is_valid, which is mostly fine.
//
// We could be doing further checks into the internal format of the
// currency data, since there are some values that are invalid.
//
//Currency.prototype.is_valid = function() {
// return this._value instanceof BigInteger && ...;
//};
Currency.prototype.to_json = function(opts) {
if (!this.is_valid()) {
// XXX This is backwards compatible behavior, but probably not very good.
return 'XRP';
}
var currency;
var fullName = opts && opts.full_name ? " - " + opts.full_name : "";
// Any currency with standard properties and a valid code can be abbreviated
// in the JSON wire format as the three character code.
if (/^[A-Z0-9]{3}$/.test(this._iso_code) && !this.has_interest()) {
currency = this._iso_code + fullName;
// If there is interest, append the annual interest to the full currency name
} else if (this.has_interest()) {
var decimals = opts ? opts.decimals : undefined;
currency = this._iso_code + fullName + " (" + this.get_interest_percentage_at(this._interest_start + 3600 * 24 * 365, decimals) + "%pa)";
} else {
// Fallback to returning the raw currency hex
currency = this.to_hex();
// XXX This is to maintain backwards compatibility, but it is very, very odd
// behavior, so we should deprecate it and get rid of it as soon as
// possible.
if (currency === Currency.HEX_ONE) {
currency = 1;
}
}
return currency;
};
Currency.prototype.to_human = function(opts) {
// to_human() will always print the human-readable currency code if available.
return this.to_json(opts);
};
Currency.prototype.get_iso = function() {
return this._iso_code;
};
exports.Currency = Currency;

59
src/js/ripple/float.js Normal file
View File

@@ -0,0 +1,59 @@
/**
* IEEE 754 floating-point.
*
* Supports single- or double-precision
*/
var Float = exports.Float = {};
var allZeros = /^0+$/;
var allOnes = /^1+$/;
Float.fromBytes = function(bytes) {
// Render in binary. Hackish.
var b = '';
for (var i = 0, n = bytes.length; i < n; i++) {
var bits = (bytes[i] & 0xff).toString(2);
while (bits.length < 8) {
bits = '0' + bits;
}
b += bits;
}
// Determine configuration. This could have all been precomputed but it is fast enough.
var exponentBits = bytes.length === 4 ? 4 : 11;
var mantissaBits = (bytes.length * 8) - exponentBits - 1;
var bias = Math.pow(2, exponentBits - 1) - 1;
var minExponent = 1 - bias - mantissaBits;
// Break up the binary representation into its pieces for easier processing.
var s = b[0];
var e = b.substring(1, exponentBits + 1);
var m = b.substring(exponentBits + 1);
var value = 0;
var multiplier = (s === '0' ? 1 : -1);
if (allZeros.test(e)) {
// Zero or denormalized
if (!allZeros.test(m)) {
value = parseInt(m, 2) * Math.pow(2, minExponent);
}
} else if (allOnes.test(e)) {
// Infinity or NaN
if (allZeros.test(m)) {
value = Infinity;
} else {
value = NaN;
}
} else {
// Normalized
var exponent = parseInt(e, 2) - bias;
var mantissa = parseInt(m, 2);
value = (1 + (mantissa * Math.pow(2, -mantissaBits))) * Math.pow(2, exponent);
}
return value * multiplier;
};

View File

@@ -0,0 +1,25 @@
/**
* Prefix for hashing functions.
*
* These prefixes are inserted before the source material used to
* generate various hashes. This is done to put each hash in its own
* "space." This way, two different types of objects with the
* same binary data will produce different hashes.
*
* Each prefix is a 4-byte value with the last byte set to zero
* and the first three bytes formed from the ASCII equivalent of
* some arbitrary string. For example "TXN".
*/
// transaction plus signature to give transaction ID
exports.HASH_TX_ID = 0x54584E00; // 'TXN'
// transaction plus metadata
exports.HASH_TX_NODE = 0x534E4400; // 'TND'
// inner node in tree
exports.HASH_INNER_NODE = 0x4D494E00; // 'MIN'
// leaf node in tree
exports.HASH_LEAF_NODE = 0x4D4C4E00; // 'MLN'
// inner transaction to sign
exports.HASH_TX_SIGN = 0x53545800; // 'STX'
// inner transaction to sign (TESTNET)
exports.HASH_TX_SIGN_TESTNET = 0x73747800; // 'stx'

107
src/js/ripple/ieee754.js Normal file
View File

@@ -0,0 +1,107 @@
// Convert a JavaScript number to IEEE-754 Double Precision
// value represented as an array of 8 bytes (octets)
//
// Based on:
// http://cautionsingularityahead.blogspot.com/2010/04/javascript-and-ieee754-redux.html
//
// Found and modified from:
// https://gist.github.com/bartaz/1119041
var Float = exports.Float = {};
Float.toIEEE754 = function(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1;
// Compute sign, exponent, fraction
var s, e, f;
if (isNaN(v)) {
e = (1 << bias) - 1; f = 1; s = 0;
}
else if (v === Infinity || v === -Infinity) {
e = (1 << bias) - 1; f = 0; s = (v < 0) ? 1 : 0;
}
else if (v === 0) {
e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
}
else {
s = v < 0;
v = Math.abs(v);
if (v >= Math.pow(2, 1 - bias)) {
var ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
e = ln + bias;
f = v * Math.pow(2, fbits - ln) - Math.pow(2, fbits);
}
else {
e = 0;
f = v / Math.pow(2, 1 - bias - fbits);
}
}
// Pack sign, exponent, fraction
var i, bits = [];
for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); }
for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); }
bits.push(s ? 1 : 0);
bits.reverse();
var str = bits.join('');
// Bits to bytes
var bytes = [];
while (str.length) {
bytes.push(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
}
Float.fromIEEE754 = function(bytes, ebits, fbits) {
// Bytes to bits
var bits = [];
for (var i = bytes.length; i; i -= 1) {
var byte = bytes[i - 1];
for (var j = 8; j; j -= 1) {
bits.push(byte % 2 ? 1 : 0); byte = byte >> 1;
}
}
bits.reverse();
var str = bits.join('');
// Unpack sign, exponent, fraction
var bias = (1 << (ebits - 1)) - 1;
var s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
var e = parseInt(str.substring(1, 1 + ebits), 2);
var f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
}
else if (e > 0) {
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
}
else if (f !== 0) {
return s * Math.pow(2, -(bias-1)) * (f / Math.pow(2, fbits));
}
else {
return s * 0;
}
}
Float.fromIEEE754Double = function(b) { return Float.fromIEEE754(b, 11, 52); }
Float.toIEEE754Double = function(v) { return Float.toIEEE754(v, 11, 52); }
Float.fromIEEE754Single = function(b) { return Float.fromIEEE754(b, 8, 23); }
Float.toIEEE754Single = function(v) { return Float.toIEEE754(v, 8, 23); }
// Convert array of octets to string binary representation
// by bartaz
Float.toIEEE754DoubleString = function(v) {
return exports.toIEEE754Double(v)
.map(function(n){ for(n = n.toString(2);n.length < 8;n="0"+n); return n })
.join('')
.replace(/(.)(.{11})(.{52})/, "$1 $2 $3")
}

View File

@@ -1,13 +1,23 @@
exports.Remote = require('./remote').Remote;
exports.Amount = require('./amount').Amount;
exports.Currency = require('./currency').Currency;
exports.Base = require('./base').Base;
exports.UInt160 = require('./amount').UInt160;
exports.Seed = require('./amount').Seed;
exports.Transaction = require('./transaction').Transaction;
exports.Meta = require('./meta').Meta;
exports.utils = require('./utils');
exports.Remote = require('./remote').Remote;
exports.Request = require('./request').Request;
exports.Amount = require('./amount').Amount;
exports.Account = require('./account').Account;
exports.Transaction = require('./transaction').Transaction;
exports.Currency = require('./currency').Currency;
exports.Base = require('./base').Base;
exports.UInt160 = require('./uint160').UInt160;
exports.UInt256 = require('./uint256').UInt256;
exports.Seed = require('./seed').Seed;
exports.Meta = require('./meta').Meta;
exports.SerializedObject = require('./serializedobject').SerializedObject;
exports.RippleError = require('./rippleerror').RippleError;
exports.Message = require('./message').Message;
exports.VaultClient = require('./vaultclient').VaultClient;
exports.AuthInfo = require('./authinfo').AuthInfo;
exports.RippleTxt = require('./rippletxt').RippleTxt;
exports.binformat = require('./binformat');
exports.utils = require('./utils');
exports.Server = require('./server').Server;
// Important: We do not guarantee any specific version of SJCL or for any
// specific features to be included. The version and configuration may change at
@@ -16,8 +26,34 @@ exports.utils = require('./utils');
// However, for programs that are tied to a specific version of ripple.js like
// the official client, it makes sense to expose the SJCL instance so we don't
// have to include it twice.
exports.sjcl = require('../../../build/sjcl');
exports.sjcl = require('./utils').sjcl;
exports.config = require('./config');
exports.config = require('./config');
// camelCase to under_scored API conversion
function attachUnderscored(c) {
var o = exports[c];
Object.keys(o.prototype).forEach(function(key) {
var UPPERCASE = /([A-Z]{1})[a-z]+/g;
if (!UPPERCASE.test(key)) {
return;
}
var underscored = key.replace(UPPERCASE, function(c) {
return '_' + c.toLowerCase();
});
o.prototype[underscored] = o.prototype[key];
});
};
[ 'Remote',
'Request',
'Transaction',
'Account',
'Server'
].forEach(attachUnderscored);
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,26 +1,21 @@
var sjcl = require('../../../build/sjcl');
var sjcl = require('./utils').sjcl;
var UInt160 = require('./uint160').UInt160;
var UInt256 = require('./uint256').UInt256;
var Base = require('./base').Base;
var KeyPair = function ()
{
this._curve = sjcl.ecc.curves['c256'];
function KeyPair() {
this._curve = sjcl.ecc.curves.c256;
this._secret = null;
this._pubkey = null;
};
KeyPair.from_bn_secret = function (j)
{
if (j instanceof this) {
return j.clone();
} else {
return (new this()).parse_bn_secret(j);
}
KeyPair.from_bn_secret = function(j) {
return (j instanceof this) ? j.clone() : (new this()).parse_bn_secret(j);
};
KeyPair.prototype.parse_bn_secret = function (j)
{
this._secret = new sjcl.ecc.ecdsa.secretKey(sjcl.ecc.curves['c256'], j);
KeyPair.prototype.parse_bn_secret = function(j) {
this._secret = new sjcl.ecc.ecdsa.secretKey(sjcl.ecc.curves.c256, j);
return this;
};
@@ -29,8 +24,7 @@ KeyPair.prototype.parse_bn_secret = function (j)
*
* @private
*/
KeyPair.prototype._pub = function ()
{
KeyPair.prototype._pub = function() {
var curve = this._curve;
if (!this._pubkey && this._secret) {
@@ -41,27 +35,64 @@ KeyPair.prototype._pub = function ()
return this._pubkey;
};
/**
* Returns public key in compressed format as bit array.
*
* @private
*/
KeyPair.prototype._pub_bits = function() {
var pub = this._pub();
if (!pub) {
return null;
}
var point = pub._point, y_even = point.y.mod(2).equals(0);
return sjcl.bitArray.concat(
[sjcl.bitArray.partial(8, y_even ? 0x02 : 0x03)],
point.x.toBits(this._curve.r.bitLength())
);
};
/**
* Returns public key as hex.
*
* Key will be returned as a compressed pubkey - 33 bytes converted to hex.
*/
KeyPair.prototype.to_hex_pub = function ()
{
var pub = this._pub();
if (!pub) return null;
KeyPair.prototype.to_hex_pub = function() {
var bits = this._pub_bits();
var point = pub._point, y_even = point.y.mod(2).equals(0);
return sjcl.codec.hex.fromBits(sjcl.bitArray.concat(
[sjcl.bitArray.partial(8, y_even ? 0x02 : 0x03)],
point.x.toBits(this._curve.r.bitLength())
)).toUpperCase();
if (!bits) {
return null;
}
return sjcl.codec.hex.fromBits(bits).toUpperCase();
};
KeyPair.prototype.sign = function (hash)
{
function SHA256_RIPEMD160(bits) {
return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
}
KeyPair.prototype.get_address = function() {
var bits = this._pub_bits();
if (!bits) {
return null;
}
var hash = SHA256_RIPEMD160(bits);
var address = UInt160.from_bits(hash);
address.set_version(Base.VER_ACCOUNT_ID);
return address;
};
KeyPair.prototype.sign = function(hash) {
hash = UInt256.from_json(hash);
return this._secret.signDER(hash.to_bits(), 0);
var sig = this._secret.sign(hash.to_bits(), 0);
sig = this._secret.canonicalizeSignature(sig);
return this._secret.encodeDER(sig);
};
exports.KeyPair = KeyPair;

167
src/js/ripple/ledger.js Normal file
View File

@@ -0,0 +1,167 @@
// Ledger
var Transaction = require('./transaction').Transaction;
var SHAMap = require('./shamap').SHAMap;
var SHAMapTreeNode = require('./shamap').SHAMapTreeNode;
var SerializedObject = require('./serializedobject').SerializedObject;
var stypes = require('./serializedtypes');
var UInt160 = require('./uint160').UInt160;
var Currency = require('./currency').Currency;
var stypes = require('./serializedtypes');
var sjcl = require('./utils').sjcl;
var Crypt = require('./crypt').Crypt;
function Ledger()
{
this.ledger_json = {};
}
Ledger.from_json = function (v) {
var ledger = new Ledger();
ledger.parse_json(v);
return ledger;
};
Ledger.space = require('./ledgerspaces');
/**
* Generate the key for an AccountRoot entry.
*
* @param {String|UInt160} account Ripple Account
* @return {UInt256}
*/
Ledger.calcAccountRootEntryHash =
Ledger.prototype.calcAccountRootEntryHash = function (account) {
account = UInt160.from_json(account);
var index = new SerializedObject();
index.append([0, Ledger.space.account.charCodeAt(0)]);
index.append(account.to_bytes());
return index.hash();
};
/**
* Generate the key for an Offer entry.
*
* @param {String|UInt160} account Ripple Account
* @param {Number} sequence Sequence number of the OfferCreate transaction
* that instantiated this offer.
* @return {UInt256}
*/
Ledger.calcOfferEntryHash =
Ledger.prototype.calcOfferEntryHash = function (account, sequence) {
account = UInt160.from_json(account);
sequence = parseInt(sequence);
var index = new SerializedObject();
index.append([0, Ledger.space.offer.charCodeAt(0)]);
index.append(account.to_bytes());
stypes.Int32.serialize(index, sequence);
return index.hash();
};
/**
* Generate the key for a RippleState entry.
*
* The ordering of the two account parameters does not matter.
*
* @param {String|UInt160} account1 First Ripple Account
* @param {String|UInt160} account2 Second Ripple Account
* @param {String|Currency} currency The currency code
* @return {UInt256}
*/
Ledger.calcRippleStateEntryHash =
Ledger.prototype.calcRippleStateEntryHash = function (account1, account2, currency) {
currency = Currency.from_json(currency);
account1 = UInt160.from_json(account1);
account2 = UInt160.from_json(account2);
if (!account1.is_valid()) {
throw new Error("Invalid first account");
}
if (!account2.is_valid()) {
throw new Error("Invalid second account");
}
if (!currency.is_valid()) {
throw new Error("Invalid currency");
}
// The lower ID has to come first
if (account1.to_bn().greaterEquals(account2.to_bn())) {
var tmp = account2;
account2 = account1;
account1 = tmp;
}
var index = new SerializedObject();
index.append([0, Ledger.space.rippleState.charCodeAt(0)]);
index.append(account1.to_bytes());
index.append(account2.to_bytes());
index.append(currency.to_bytes());
return index.hash();
};
Ledger.prototype.parse_json = function (v) {
this.ledger_json = v;
};
Ledger.prototype.calc_tx_hash = function () {
var tx_map = new SHAMap();
this.ledger_json.transactions.forEach(function (tx_json) {
var tx = Transaction.from_json(tx_json);
var meta = SerializedObject.from_json(tx_json.metaData);
var data = new SerializedObject();
stypes.VariableLength.serialize(data, tx.serialize().to_hex());
stypes.VariableLength.serialize(data, meta.to_hex());
tx_map.add_item(tx.hash(), data, SHAMapTreeNode.TYPE_TRANSACTION_MD);
});
return tx_map.hash();
};
/**
* @param options.sanity_test {Boolean}
*
* If `true`, will serialize each accountState item to binary and then back to
* json before finally serializing for hashing. This is mostly to expose any
* issues with ripple-lib's binary <--> json codecs.
*
*/
Ledger.prototype.calc_account_hash = function (options) {
var account_map = new SHAMap();
var erred;
this.ledger_json.accountState.forEach(function (le) {
var data = SerializedObject.from_json(le);
if (options != null && options.sanity_test) {
try {
var json = data.to_json();
data = SerializedObject.from_json(json);
} catch (e) {
console.log("account state item: ", le);
console.log("to_json() ",json);
console.log("exception: ", e);
erred = true;
}
};
account_map.add_item(le.index, data, SHAMapTreeNode.TYPE_ACCOUNT_STATE);
});
if (erred) {
throw new Error("There were errors with sanity_test"); // all logged above
}
return account_map.hash();
};
exports.Ledger = Ledger;

View File

@@ -0,0 +1,22 @@
/**
* Ripple ledger namespace prefixes.
*
* The Ripple ledger is a key-value store. In order to avoid name collisions,
* names are partitioned into namespaces.
*
* Each namespace is just a single character prefix.
*/
module.exports = {
account : 'a',
dirNode : 'd',
generatorMap : 'g',
nickname : 'n',
rippleState : 'r',
offer : 'o', // Entry for an offer.
ownerDir : 'O', // Directory of things owned by an account.
bookDir : 'B', // Directory of order books.
contract : 'c',
skipList : 's',
amendment : 'f',
feeSettings : 'e'
};

109
src/js/ripple/log.js Normal file
View File

@@ -0,0 +1,109 @@
/**
* Logging functionality for ripple-lib and any applications built on it.
*/
function Log(namespace) {
if (!namespace) {
this._namespace = [];
} else if (Array.isArray(namespace)) {
this._namespace = namespace;
} else {
this._namespace = [''+namespace];
}
this._prefix = this._namespace.concat(['']).join(': ');
};
/**
* Create a sub-logger.
*
* You can have a hierarchy of loggers.
*
* @example
*
* var log = require('ripple').log.sub('server');
*
* log.info('connection successful');
* // prints: 'server: connection successful'
*/
Log.prototype.sub = function(namespace) {
var subNamespace = this._namespace.slice();
if (namespace && typeof namespace === 'string') {
subNamespace.push(namespace);
}
var subLogger = new Log(subNamespace);
subLogger._setParent(this);
return subLogger;
};
Log.prototype._setParent = function(parentLogger) {
this._parent = parentLogger;
};
Log.makeLevel = function(level) {
return function() {
var args = Array.prototype.slice.call(arguments);
args[0] = this._prefix + args[0];
Log.engine.logObject.apply(Log, args);
};
};
Log.prototype.debug = Log.makeLevel(1);
Log.prototype.info = Log.makeLevel(2);
Log.prototype.warn = Log.makeLevel(3);
Log.prototype.error = Log.makeLevel(4);
/**
* Basic logging connector.
*
* This engine has no formatting and works with the most basic of 'console.log'
* implementations. This is the logging engine used in Node.js.
*/
var BasicLogEngine = {
logObject: function logObject(msg) {
var args = Array.prototype.slice.call(arguments, 1);
args = args.map(function(arg) {
return JSON.stringify(arg, null, 2);
});
args.unshift(msg);
console.log.apply(console, args);
}
};
/**
* Null logging connector.
*
* This engine simply swallows all messages. Used when console.log is not
* available.
*/
var NullLogEngine = {
logObject: function() {}
};
Log.engine = NullLogEngine;
if (console && console.log) {
Log.engine = BasicLogEngine;
}
/**
* Provide a root logger as our main export.
*
* This means you can use the logger easily on the fly:
* ripple.log.debug('My object is', myObj);
*/
module.exports = new Log();
/**
* This is the logger for ripple-lib internally.
*/
module.exports.internal = module.exports.sub();
/**
* Expose the class as well.
*/
module.exports.Log = Log;

30
src/js/ripple/log.web.js Normal file
View File

@@ -0,0 +1,30 @@
var exports = module.exports = require('./log.js');
/**
* Log engine for browser consoles.
*
* Browsers tend to have better consoles that support nicely formatted
* JavaScript objects. This connector passes objects through to the logging
* function without any stringification.
*/
var InteractiveLogEngine = {
logObject: function (msg, obj) {
var args = Array.prototype.slice.call(arguments, 1);
args = args.map(function(arg) {
if (/MSIE/.test(navigator.userAgent)) {
return JSON.stringify(arg, null, 2);
} else {
return arg;
}
});
args.unshift(msg);
console.log.apply(console, args);
}
};
if (window.console && window.console.log) {
exports.Log.engine = InteractiveLogEngine;
}

203
src/js/ripple/message.js Normal file
View File

@@ -0,0 +1,203 @@
var async = require('async');
var crypto = require('crypto');
var sjcl = require('./utils').sjcl;
var Remote = require('./remote').Remote;
var Seed = require('./seed').Seed;
var KeyPair = require('./keypair').KeyPair;
var Account = require('./account').Account;
var UInt160 = require('./uint160').UInt160;
// Message class (static)
var Message = {};
Message.HASH_FUNCTION = sjcl.hash.sha512.hash;
Message.MAGIC_BYTES = 'Ripple Signed Message:\n';
var REGEX_HEX = /^[0-9a-fA-F]+$/;
var REGEX_BASE64 = /^([A-Za-z0-9\+]{4})*([A-Za-z0-9\+]{2}==)|([A-Za-z0-9\+]{3}=)?$/;
/**
* Produce a Base64-encoded signature on the given message with
* the string 'Ripple Signed Message:\n' prepended.
*
* Note that this signature uses the signing function that includes
* a recovery_factor to be able to extract the public key from the signature
* without having to pass the public key along with the signature.
*
* @static
*
* @param {String} message
* @param {sjcl.ecc.ecdsa.secretKey|Any format accepted by Seed.from_json} secret_key
* @param {RippleAddress} [The first key] account Field to specify the signing account.
* If this is omitted the first account produced by the secret generator will be used.
* @returns {Base64-encoded String} signature
*/
Message.signMessage = function(message, secret_key, account) {
return Message.signHash(Message.HASH_FUNCTION(Message.MAGIC_BYTES + message), secret_key, account);
};
/**
* Produce a Base64-encoded signature on the given hex-encoded hash.
*
* Note that this signature uses the signing function that includes
* a recovery_factor to be able to extract the public key from the signature
* without having to pass the public key along with the signature.
*
* @static
*
* @param {bitArray|Hex-encoded String} hash
* @param {sjcl.ecc.ecdsa.secretKey|Any format accepted by Seed.from_json} secret_key
* @param {RippleAddress} [The first key] account Field to specify the signing account.
* If this is omitted the first account produced by the secret generator will be used.
* @returns {Base64-encoded String} signature
*/
Message.signHash = function(hash, secret_key, account) {
if (typeof hash === 'string' && /^[0-9a-fA-F]+$/.test(hash)) {
hash = sjcl.codec.hex.toBits(hash);
}
if (typeof hash !== 'object' || hash.length <= 0 || typeof hash[0] !== 'number') {
throw new Error('Hash must be a bitArray or hex-encoded string');
}
if (!(secret_key instanceof sjcl.ecc.ecdsa.secretKey)) {
secret_key = Seed.from_json(secret_key).get_key(account)._secret;
}
var signature_bits = secret_key.signWithRecoverablePublicKey(hash);
var signature_base64 = sjcl.codec.base64.fromBits(signature_bits);
return signature_base64;
};
/**
* Verify the signature on a given message.
*
* Note that this function is asynchronous.
* The ripple-lib remote is used to check that the public
* key extracted from the signature corresponds to one that is currently
* active for the given account.
*
* @static
*
* @param {String} data.message
* @param {RippleAddress} data.account
* @param {Base64-encoded String} data.signature
* @param {ripple-lib Remote} remote
* @param {Function} callback
*
* @callback callback
* @param {Error} error
* @param {boolean} is_valid true if the signature is valid, false otherwise
*/
Message.verifyMessageSignature = function(data, remote, callback) {
if (typeof data.message === 'string') {
data.hash = Message.HASH_FUNCTION(Message.MAGIC_BYTES + data.message);
} else {
return callback(new Error('Data object must contain message field to verify signature'));
}
return Message.verifyHashSignature(data, remote, callback);
};
/**
* Verify the signature on a given hash.
*
* Note that this function is asynchronous.
* The ripple-lib remote is used to check that the public
* key extracted from the signature corresponds to one that is currently
* active for the given account.
*
* @static
*
* @param {bitArray|Hex-encoded String} data.hash
* @param {RippleAddress} data.account
* @param {Base64-encoded String} data.signature
* @param {ripple-lib Remote} remote
* @param {Function} callback
*
* @callback callback
* @param {Error} error
* @param {boolean} is_valid true if the signature is valid, false otherwise
*/
Message.verifyHashSignature = function(data, remote, callback) {
var hash,
account,
signature;
if(typeof callback !== 'function') {
throw new Error('Must supply callback function');
}
hash = data.hash;
if (hash && typeof hash === 'string' && REGEX_HEX.test(hash)) {
hash = sjcl.codec.hex.toBits(hash);
}
if (typeof hash !== 'object' || hash.length <= 0 || typeof hash[0] !== 'number') {
return callback(new Error('Hash must be a bitArray or hex-encoded string'));
}
account = data.account || data.address;
if (!account || !UInt160.from_json(account).is_valid()) {
return callback(new Error('Account must be a valid ripple address'));
}
signature = data.signature;
if (typeof signature !== 'string' || !REGEX_BASE64.test(signature)) {
return callback(new Error('Signature must be a Base64-encoded string'));
}
signature = sjcl.codec.base64.toBits(signature);
if (!(remote instanceof Remote) || remote.state !== 'online') {
return callback(new Error('Must supply connected Remote to verify signature'));
}
function recoverPublicKey (async_callback) {
var public_key;
try {
public_key = sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
} catch (err) {
return async_callback(err);
}
if (public_key) {
async_callback(null, public_key);
} else {
async_callback(new Error('Could not recover public key from signature'));
}
};
function checkPublicKeyIsValid (public_key, async_callback) {
// Get hex-encoded public key
var key_pair = new KeyPair();
key_pair._pubkey = public_key;
var public_key_hex = key_pair.to_hex_pub();
var account_class_instance = new Account(remote, account);
account_class_instance.publicKeyIsActive(public_key_hex, async_callback);
};
var steps = [
recoverPublicKey,
checkPublicKeyIsValid
];
async.waterfall(steps, callback);
};
exports.Message = Message;

View File

@@ -1,37 +1,56 @@
var extend = require('extend');
var utils = require('./utils');
var extend = require('extend');
var utils = require('./utils');
var UInt160 = require('./uint160').UInt160;
var Amount = require('./amount').Amount;
var Amount = require('./amount').Amount;
/**
* Meta data processing facility.
* Meta data processing facility
*/
var Meta = function (raw_data)
{
this.nodes = [];
for (var i = 0, l = raw_data.AffectedNodes.length; i < l; i++) {
var an = raw_data.AffectedNodes[i],
result = {};
function Meta(raw_data) {
var self = this;
["CreatedNode", "ModifiedNode", "DeletedNode"].forEach(function (x) {
if (an[x]) result.diffType = x;
});
this.nodes = [ ];
if (!result.diffType) return null;
raw_data.AffectedNodes.forEach(function(an) {
var result = { };
an = an[result.diffType];
if ((result.diffType = self.diffType(an))) {
an = an[result.diffType];
result.entryType = an.LedgerEntryType;
result.ledgerIndex = an.LedgerIndex;
result.entryType = an.LedgerEntryType;
result.ledgerIndex = an.LedgerIndex;
result.fields = extend({}, an.PreviousFields, an.NewFields, an.FinalFields);
result.fieldsPrev = an.PreviousFields || {};
result.fieldsNew = an.NewFields || {};
result.fieldsFinal = an.FinalFields || {};
result.fields = extend({}, an.PreviousFields, an.NewFields, an.FinalFields);
result.fieldsPrev = an.PreviousFields || {};
result.fieldsNew = an.NewFields || {};
result.fieldsFinal = an.FinalFields || {};
// getAffectedBooks will set this
// result.bookKey = undefined;
this.nodes.push(result);
self.nodes.push(result);
}
});
};
Meta.node_types = [
'CreatedNode',
'ModifiedNode',
'DeletedNode'
];
Meta.prototype.diffType = function(an) {
var result = false;
for (var i=0; i<Meta.node_types.length; i++) {
var x = Meta.node_types[i];
if (an.hasOwnProperty(x)) {
result = x;
break;
}
}
return result;
};
/**
@@ -69,29 +88,41 @@ var Meta = function (raw_data)
* The second parameter to the callback is the index of the node in the metadata
* (first entry is index 0).
*/
Meta.prototype.each = function (fn)
{
Meta.prototype.each = function(fn) {
for (var i = 0, l = this.nodes.length; i < l; i++) {
fn(this.nodes[i], i);
}
};
([
'forEach',
'map',
'filter',
'every',
'reduce'
]).forEach(function(fn) {
Meta.prototype[fn] = function() {
return Array.prototype[fn].apply(this.nodes, arguments);
};
});
var amountFieldsAffectingIssuer = [
"LowLimit", "HighLimit", "TakerPays", "TakerGets"
'LowLimit',
'HighLimit',
'TakerPays',
'TakerGets'
];
Meta.prototype.getAffectedAccounts = function ()
{
var accounts = [];
Meta.prototype.getAffectedAccounts = function() {
var accounts = [ ];
// This code should match the behavior of the C++ method:
// TransactionMetaSet::getAffectedAccounts
this.each(function (an) {
var fields = (an.diffType === "CreatedNode") ? an.fieldsNew : an.fieldsFinal;
this.nodes.forEach(function(an) {
var fields = (an.diffType === 'CreatedNode') ? an.fieldsNew : an.fieldsFinal;
for (var i in fields) {
var field = fields[i];
if ("string" === typeof field && UInt160.is_valid(field)) {
if (typeof field === 'string' && UInt160.is_valid(field)) {
accounts.push(field);
} else if (amountFieldsAffectingIssuer.indexOf(i) !== -1) {
var amount = Amount.from_json(field);
@@ -103,35 +134,41 @@ Meta.prototype.getAffectedAccounts = function ()
}
});
accounts = utils.arrayUnique(accounts);
return accounts;
return utils.arrayUnique(accounts);
};
Meta.prototype.getAffectedBooks = function ()
{
var books = [];
Meta.prototype.getAffectedBooks = function() {
var books = [ ];
this.each(function (an) {
if (an.entryType !== 'Offer') return;
this.nodes.forEach(function(an) {
if (an.entryType !== 'Offer') {
return;
}
var gets = Amount.from_json(an.fields.TakerGets);
var pays = Amount.from_json(an.fields.TakerPays);
var getsKey = gets.currency().to_json();
if (getsKey !== 'XRP') getsKey += '/' + gets.issuer().to_json();
if (getsKey !== 'XRP') {
getsKey += '/' + gets.issuer().to_json();
}
var paysKey = pays.currency().to_json();
if (paysKey !== 'XRP') paysKey += '/' + pays.issuer().to_json();
if (paysKey !== 'XRP') {
paysKey += '/' + pays.issuer().to_json();
}
var key = getsKey + ":" + paysKey;
var key = [ getsKey, paysKey ].join(':');
// Hell of a lot of work, so we are going to cache this. We can use this
// later to good effect in OrderBook.notify to make sure we only process
// pertinent offers.
an.bookKey = key;
books.push(key);
});
books = utils.arrayUnique(books);
return books;
return utils.arrayUnique(books);
};
exports.Meta = Meta;

View File

@@ -1,58 +0,0 @@
//
// Access to the Ripple network via multiple untrusted servers or a single trusted server.
//
// Overview:
// Network configuration.
// Can leverage local storage to remember network configuration
// Aquires the network
// events:
// online
// offline
//
var remote = require("./remote.js");
var opts_default = {
DEFAULT_VALIDATORS_SITE : "redstem.com",
ips = {
}
};
//
// opts : {
// cache : undefined || {
// get : function () { return cached_value; },
// set : function (value) { cached_value = value; },
// },
//
// // Where to get validators.txt if needed.
// DEFAULT_VALIDATORS_SITE : _domain_,
//
// // Validator.txt to use.
// validators : _txt_,
// }
//
var Network = function (opts) {
};
// Set the network configuration.
Network.protocol.configure = function () {
};
// Target state: connectted
Network.protocol.start = function () {
};
// Target state: disconnect
Network.protocol.stop = function () {
};
exports.Network = Network;
// vim:sw=2:sts=2:ts=8:et

View File

@@ -8,19 +8,17 @@
// var network = require("./network.js");
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var extend = require('extend');
var Amount = require('./amount').Amount;
var UInt160 = require('./uint160').UInt160;
var Currency = require('./currency').Currency;
var extend = require('extend');
var OrderBook = function (remote, currency_gets, issuer_gets, currency_pays, issuer_pays) {
function OrderBook(remote, currency_gets, issuer_gets, currency_pays, issuer_pays, key) {
EventEmitter.call(this);
var self = this;
var self = this;
this._remote = remote;
this._currency_gets = currency_gets;
@@ -28,44 +26,50 @@ var OrderBook = function (remote, currency_gets, issuer_gets, currency_pays, iss
this._currency_pays = currency_pays;
this._issuer_pays = issuer_pays;
this._subs = 0;
this._key = key;
// We consider ourselves synchronized if we have a current copy of the offers,
// we are online and subscribed to updates.
this._sync = false;
this._sync = false;
// Offers
this._offers = [];
this._offers = [ ];
this.on('newListener', function (type, listener) {
if (OrderBook.subscribe_events.indexOf(type) !== -1) {
if (!self._subs && 'open' === self._remote._online_state) {
function listenerAdded(type, listener) {
if (~OrderBook.subscribe_events.indexOf(type)) {
self._subs += 1;
if (self._subs === 1 && self._remote._connected) {
self._subscribe();
}
self._subs += 1;
}
});
};
this.on('removeListener', function (type, listener) {
this.on('newListener', listenerAdded);
function listenerRemoved(type, listener) {
if (~OrderBook.subscribe_events.indexOf(type)) {
self._subs -= 1;
self._subs -= 1;
if (!self._subs && self._remote._connected) {
self._sync = false;
self._remote.request_unsubscribe()
.books([self.to_json()])
.request();
.books([self.to_json()])
.request();
}
}
};
this.on('removeListener', listenerRemoved);
// ST: This *should* call _prepareSubscribe.
this._remote.on('prepare_subscribe', function(request) {
self._subscribe(request);
});
this._remote.on('connect', function () {
if (self._subs) {
self._subscribe();
}
});
this._remote.on('disconnect', function () {
function remoteDisconnected() {
self._sync = false;
});
};
this._remote.on('disconnect', remoteDisconnected);
return this;
};
@@ -82,36 +86,66 @@ OrderBook.subscribe_events = ['transaction', 'model', 'trade'];
*
* @private
*/
OrderBook.prototype._subscribe = function () {
OrderBook.prototype._subscribe = function (request) {
var self = this;
self._remote.request_subscribe()
.books([self.to_json()], true)
.on('error', function () {
// XXX What now?
})
.on('success', function (res) {
if (self.is_valid() && self._subs) {
var request = this._remote.request_subscribe();
request.addBook(self.to_json(), true);
request.once('success', function(res) {
self._sync = true;
self._offers = res.offers;
self.emit('model', self._offers);
})
.request();
});
request.once('error', function(err) {
// XXX What now?
});
request.request();
}
};
/**
* Adds this orderbook to a subscription request.
// ST: Currently this is not working because the server cannot give snapshots
// for more than one order book in the same subscribe message.
OrderBook.prototype._prepareSubscribe = function (request) {
var self = this;
if (self.is_valid() && self._subs) {
request.addBook(self.to_json(), true);
request.once('success', function(res) {
self._sync = true;
self._offers = res.offers;
self.emit('model', self._offers);
});
request.once('error', function(err) {
// XXX What now?
});
}
};
*/
OrderBook.prototype.to_json = function () {
var json = {
'taker_gets': {
'currency': this._currency_gets
taker_gets: {
currency: this._currency_gets
},
'taker_pays': {
'currency': this._currency_pays
taker_pays: {
currency: this._currency_pays
}
};
if (this._currency_gets !== 'XRP')
json['taker_gets']['issuer'] = this._issuer_gets;
if (this._currency_gets !== 'XRP') {
json.taker_gets.issuer = this._issuer_gets;
}
if (this._currency_pays !== 'XRP')
json['taker_pays']['issuer'] = this._issuer_pays;
if (this._currency_pays !== 'XRP') {
json.taker_pays.issuer = this._issuer_pays;
}
return json;
};
@@ -135,9 +169,9 @@ OrderBook.prototype.is_valid = function () {
OrderBook.prototype.trade = function(type) {
var tradeStr = '0'
+ (this['_currency_' + type] === 'XRP') ? '' : '/'
+ this['_currency_' + type ] + '/'
+ this['_issuer_' + type];
+ ((this['_currency_' + type] === 'XRP') ? '' : '/'
+ this['_currency_' + type ] + '/'
+ this['_issuer_' + type]);
return Amount.from_json(tradeStr);
};
@@ -147,14 +181,16 @@ OrderBook.prototype.trade = function(type) {
* This is only meant to be called by the Remote class. You should never have to
* call this yourself.
*/
OrderBook.prototype.notifyTx = function (message) {
OrderBook.prototype.notify = function (message) {
var self = this;
var changed = false;
var trade_gets = this.trade('gets');
var trade_pays = this.trade('pays');
message.mmeta.each(function (an) {
if (an.entryType !== 'Offer') return;
function handleTransaction(an) {
if (an.entryType !== 'Offer' || an.bookKey !== self._key) {
return;
}
var i, l, offer;
@@ -163,21 +199,27 @@ OrderBook.prototype.notifyTx = function (message) {
case 'ModifiedNode':
var deletedNode = an.diffType === 'DeletedNode';
for (i = 0, l = self._offers.length; i < l; i++) {
for (i=0, l=self._offers.length; i<l; i++) {
offer = self._offers[i];
if (offer.index === an.ledgerIndex) {
if (deletedNode) {
self._offers.splice(i, 1);
} else {
// TODO: This assumes no fields are deleted, which is probably a
// safe assumption, but should be checked.
extend(offer, an.fieldsFinal);
}
changed = true;
break;
}
}
// We don't want to count a OfferCancel as a trade
if (message.transaction.TransactionType === 'OfferCancel') return;
if (message.transaction.TransactionType === 'OfferCancel') {
return;
}
trade_gets = trade_gets.add(an.fieldsPrev.TakerGets);
trade_pays = trade_pays.add(an.fieldsPrev.TakerPays);
@@ -187,13 +229,14 @@ OrderBook.prototype.notifyTx = function (message) {
trade_pays = trade_pays.subtract(an.fieldsFinal.TakerPays);
}
break;
case 'CreatedNode':
var price = Amount.from_json(an.fields.TakerPays).ratio_human(an.fields.TakerGets);
// XXX Should use Amount#from_quality
var price = Amount.from_json(an.fields.TakerPays).ratio_human(an.fields.TakerGets, {reference_date: new Date()});
for (i = 0, l = self._offers.length; i < l; i++) {
offer = self._offers[i];
var priceItem = Amount.from_json(offer.TakerPays).ratio_human(offer.TakerGets);
var priceItem = Amount.from_json(offer.TakerPays).ratio_human(offer.TakerGets, {reference_date: new Date()});
if (price.compareTo(priceItem) <= 0) {
var obj = an.fields;
@@ -205,18 +248,26 @@ OrderBook.prototype.notifyTx = function (message) {
}
break;
}
});
};
message.mmeta.each(handleTransaction);
// Only trigger the event if the account object is actually
// subscribed - this prevents some weird phantom events from
// occurring.
if (this._subs) {
this.emit('transaction', message);
if (changed) this.emit('model', this._offers);
if (!trade_gets.is_zero()) this.emit('trade', trade_pays, trade_gets);
if (changed) {
this.emit('model', this._offers);
}
if (!trade_gets.is_zero()) {
this.emit('trade', trade_pays, trade_gets);
}
}
};
OrderBook.prototype.notifyTx = OrderBook.prototype.notify;
/**
* Get offers model asynchronously.
*
@@ -227,6 +278,7 @@ OrderBook.prototype.notifyTx = function (message) {
*/
OrderBook.prototype.offers = function (callback) {
var self = this;
if (typeof callback === 'function') {
if (this._sync) {
callback(this._offers);
@@ -234,6 +286,7 @@ OrderBook.prototype.offers = function (callback) {
this.once('model', callback);
}
}
return this;
};

86
src/js/ripple/pathfind.js Normal file
View File

@@ -0,0 +1,86 @@
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Amount = require('./amount').Amount;
var extend = require('extend');
/**
* Represents a persistent path finding request.
*
* Only one path find request is allowed per connection, so when another path
* find request is triggered it will supercede the existing one, making it emit
* the 'end' and 'superceded' events.
*/
function PathFind(remote, src_account, dst_account, dst_amount, src_currencies) {
EventEmitter.call(this);
this.remote = remote;
this.src_account = src_account;
this.dst_account = dst_account;
this.dst_amount = dst_amount;
this.src_currencies = src_currencies;
};
util.inherits(PathFind, EventEmitter);
/**
* Submits a path_find_create request to the network.
*
* This starts a path find request, superceding all previous path finds.
*
* This will be called automatically by Remote when this object is instantiated,
* so you should only have to call it if the path find was closed or superceded
* and you wish to restart it.
*/
PathFind.prototype.create = function () {
var self = this;
var req = this.remote.request_path_find_create(this.src_account,
this.dst_account,
this.dst_amount,
this.src_currencies,
handleInitialPath);
function handleInitialPath(err, msg) {
if (err) {
self.emit('error', err);
} else {
self.notify_update(msg);
}
}
// XXX We should add ourselves to prepare_subscribe or a similar mechanism so
// that we can resubscribe after a reconnection.
req.request();
};
PathFind.prototype.close = function () {
this.remote.request_path_find_close().request();
this.emit('end');
this.emit('close');
};
PathFind.prototype.notify_update = function (message) {
var src_account = message.source_account;
var dst_account = message.destination_account;
var dst_amount = Amount.from_json(message.destination_amount);
// Only pass the event along if this path find response matches what we were
// looking for.
if (this.src_account === src_account &&
this.dst_account === dst_account &&
this.dst_amount.equals(dst_amount)) {
this.emit('update', message);
}
};
PathFind.prototype.notify_superceded = function () {
// XXX If we're set to re-subscribe whenever we connect to a new server, then
// we should cancel that behavior here. See PathFind#create.
this.emit('end');
this.emit('superceded');
};
exports.PathFind = PathFind;

File diff suppressed because it is too large Load Diff

364
src/js/ripple/request.js Normal file
View File

@@ -0,0 +1,364 @@
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var UInt160 = require('./uint160').UInt160;
var Currency = require('./currency').Currency;
var RippleError = require('./rippleerror').RippleError;
var Server = require('./server').Server;
// Request events emitted:
// 'success' : Request successful.
// 'error' : Request failed.
// 'remoteError'
// 'remoteUnexpected'
// 'remoteDisconnected'
function Request(remote, command) {
EventEmitter.call(this);
this.remote = remote;
this.requested = false;
this.message = {
command: command,
id: void(0)
};
};
util.inherits(Request, EventEmitter);
Request.prototype.broadcast = function() {
this._broadcast = true;
return this.request();
};
// Send the request to a remote.
Request.prototype.request = function(remote) {
if (this.requested) {
return;
}
this.requested = true;
this.on('error', function(){});
this.emit('request', remote);
if (this._broadcast) {
this.remote._servers.forEach(function(server) {
this.setServer(server);
this.remote.request(this);
}, this);
} else {
this.remote.request(this);
}
return this;
};
Request.prototype.callback = function(callback, successEvent, errorEvent) {
var self = this;
if (this.requested || typeof callback !== 'function') {
return this;
}
var called = false;
function requestSuccess(message) {
if (!called) {
called = true;
callback.call(self, null, message);
}
};
function requestError(error) {
if (!called) {
called = true;
if (!(error instanceof RippleError)) {
error = new RippleError(error);
}
callback.call(self, error);
}
};
this.once(successEvent || 'success', requestSuccess);
this.once(errorEvent || 'error' , requestError);
this.request();
return this;
};
Request.prototype.timeout = function(duration, callback) {
var self = this;
function requested() {
self.timeout(duration, callback);
};
if (!this.requested) {
// Defer until requested
return this.once('request', requested);
}
var emit = this.emit;
var timed_out = false;
var timeout = setTimeout(function() {
timed_out = true;
if (typeof callback === 'function') {
callback();
}
emit.call(self, 'timeout');
}, duration);
this.emit = function() {
if (!timed_out) {
clearTimeout(timeout);
emit.apply(self, arguments);
}
};
return this;
};
Request.prototype.setServer = function(server) {
var selected = null;
switch (typeof server) {
case 'object':
selected = server;
break;
case 'string':
// Find server by URL
var servers = this.remote._servers;
for (var i=0, s; (s=servers[i]); i++) {
if (s._url === server) {
selected = s;
break;
}
}
break;
};
if (selected instanceof Server) {
this.server = selected;
}
return this;
};
Request.prototype.buildPath = function(build) {
if (this.remote.local_signing) {
throw new Error(
'`build_path` is completely ignored when doing local signing as '
+ '`Paths` is a component of the signed blob. The `tx_blob` is signed,'
+ 'sealed and delivered, and the txn unmodified after' );
}
if (build) {
this.message.build_path = true;
} else {
// ND: rippled currently intreprets the mere presence of `build_path` as the
// value being `truthy`
delete this.message.build_path;
}
return this;
};
Request.prototype.ledgerChoose = function(current) {
if (current) {
this.message.ledger_index = this.remote._ledger_current_index;
} else {
this.message.ledger_hash = this.remote._ledger_hash;
}
return this;
};
// Set the ledger for a request.
// - ledger_entry
// - transaction_entry
Request.prototype.ledgerHash = function(hash) {
this.message.ledger_hash = hash;
return this;
};
// Set the ledger_index for a request.
// - ledger_entry
Request.prototype.ledgerIndex = function(ledger_index) {
this.message.ledger_index = ledger_index;
return this;
};
Request.prototype.ledgerSelect = function(ledger) {
switch (ledger) {
case 'current':
case 'closed':
case 'validated':
this.message.ledger_index = ledger;
break;
default:
if (isNaN(ledger)) {
this.message.ledger_hash = ledger;
} else if ((ledger = Number(ledger))) {
this.message.ledger_index = ledger;
}
break;
}
return this;
};
Request.prototype.accountRoot = function(account) {
this.message.account_root = UInt160.json_rewrite(account);
return this;
};
Request.prototype.index = function(index) {
this.message.index = index;
return this;
};
// Provide the information id an offer.
// --> account
// --> seq : sequence number of transaction creating offer (integer)
Request.prototype.offerId = function(account, sequence) {
this.message.offer = {
account: UInt160.json_rewrite(account),
seq: sequence
};
return this;
};
// --> index : ledger entry index.
Request.prototype.offerIndex = function(index) {
this.message.offer = index;
return this;
};
Request.prototype.secret = function(secret) {
if (secret) {
this.message.secret = secret;
}
return this;
};
Request.prototype.txHash = function(hash) {
this.message.tx_hash = hash;
return this;
};
Request.prototype.txJson = function(json) {
this.message.tx_json = json;
return this;
};
Request.prototype.txBlob = function(json) {
this.message.tx_blob = json;
return this;
};
Request.prototype.rippleState = function(account, issuer, currency) {
this.message.ripple_state = {
currency : currency,
accounts : [
UInt160.json_rewrite(account),
UInt160.json_rewrite(issuer)
]
};
return this;
};
Request.prototype.accounts = function(accounts, proposed) {
if (!Array.isArray(accounts)) {
accounts = [ accounts ];
}
// Process accounts parameters
var processedAccounts = accounts.map(function(account) {
return UInt160.json_rewrite(account);
});
if (proposed) {
this.message.accounts_proposed = processedAccounts;
} else {
this.message.accounts = processedAccounts;
}
return this;
};
Request.prototype.addAccount = function(account, proposed) {
var processedAccount = UInt160.json_rewrite(account);
if (proposed) {
this.message.accounts_proposed = (this.message.accounts_proposed || []).concat(processedAccount);
} else {
this.message.accounts = (this.message.accounts || []).concat(processedAccount);
}
return this;
};
Request.prototype.rtAccounts =
Request.prototype.accountsProposed = function(accounts) {
return this.accounts(accounts, true);
};
Request.prototype.addAccountProposed = function(account) {
return this.addAccount(account, true);
};
Request.prototype.books = function(books, snapshot) {
// Reset list of books (this method overwrites the current list)
this.message.books = [ ];
for (var i=0, l=books.length; i<l; i++) {
var book = books[i];
this.addBook(book, snapshot);
}
return this;
};
Request.prototype.addBook = function(book, snapshot) {
if (!Array.isArray(this.message.books)) {
this.message.books = [ ];
}
var json = { };
function processSide(side) {
if (!book[side]) {
throw new Error('Missing ' + side);
}
var obj = json[side] = {
currency: Currency.json_rewrite(book[side].currency)
};
if (obj.currency !== 'XRP') {
obj.issuer = UInt160.json_rewrite(book[side].issuer);
}
}
[ 'taker_gets', 'taker_pays' ].forEach(processSide);
if (snapshot) {
json.snapshot = true;
}
if (book.both) {
json.both = true;
}
this.message.books.push(json);
};
exports.Request = Request;

View File

@@ -0,0 +1,33 @@
var util = require('util');
var extend = require('extend');
function RippleError(code, message) {
switch (typeof code) {
case 'object':
extend(this, code);
break;
case 'string':
this.result = code;
this.result_message = message;
break;
}
this.engine_result = this.result = (this.result || this.engine_result || this.error || 'Error');
this.engine_result_message = this.result_message = (this.result_message || this.engine_result_message || this.error_message || 'Error');
this.result_message = this.message = (this.result_message);
var stack;
if (!!Error.captureStackTrace) {
Error.captureStackTrace(this, code || this);
} else if ((stack = new Error().stack)) {
this.stack = stack;
}
};
util.inherits(RippleError, Error);
RippleError.prototype.name = 'RippleError';
exports.RippleError = RippleError;

133
src/js/ripple/rippletxt.js Normal file
View File

@@ -0,0 +1,133 @@
var request = require('superagent');
var Currency = require('./currency').Currency;
var RippleTxt = {
txts : { }
};
RippleTxt.urlTemplates = [
'https://{{domain}}/ripple.txt',
'https://www.{{domain}}/ripple.txt',
'https://ripple.{{domain}}/ripple.txt',
'http://{{domain}}/ripple.txt',
'http://www.{{domain}}/ripple.txt',
'http://ripple.{{domain}}/ripple.txt'
];
/**
* Gets the ripple.txt file for the given domain
* @param {string} domain - Domain to retrieve file from
* @param {function} fn - Callback function
*/
RippleTxt.get = function(domain, fn) {
var self = this;
if (self.txts[domain]) {
return fn(null, self.txts[domain]);
}
;(function nextUrl(i) {
var url = RippleTxt.urlTemplates[i];
if (!url) {
return fn(new Error('No ripple.txt found'));
}
url = url.replace('{{domain}}', domain);
request.get(url, function(err, resp) {
if (err || !resp.text) {
return nextUrl(++i);
}
var sections = self.parse(resp.text);
self.txts[domain] = sections;
fn(null, sections);
});
})(0);
};
/**
* Parse a ripple.txt file
* @param {string} txt - Unparsed ripple.txt data
*/
RippleTxt.parse = function(txt) {
var currentSection = '';
var sections = { };
txt = txt.replace(/\r?\n/g, '\n').split('\n');
for (var i = 0, l = txt.length; i < l; i++) {
var line = txt[i];
if (!line.length || line[0] === '#') {
continue;
}
if (line[0] === '[' && line[line.length - 1] === ']') {
currentSection = line.slice(1, line.length - 1);
sections[currentSection] = [];
} else {
line = line.replace(/^\s+|\s+$/g, '');
if (sections[currentSection]) {
sections[currentSection].push(line);
}
}
}
return sections;
};
/**
* extractDomain
* attempt to extract the domain from a given url
* returns the url if unsuccessful
* @param {Object} url
*/
RippleTxt.extractDomain = function (url) {
match = /[^.]*\.[^.]{2,3}(?:\.[^.]{2,3})?([^.\?][^\?.]+?)?$/.exec(url);
return match && match[0] ? match[0] : url;
};
/**
* getCurrencies
* returns domain, issuer account and currency object
* for each currency found in the domain's ripple.txt file
* @param {Object} domain
* @param {Object} fn
*/
RippleTxt.getCurrencies = function(domain, fn) {
domain = RippleTxt.extractDomain(domain);
this.get(domain, function(err, txt) {
if (err) {
return fn(err);
}
if (err || !txt.currencies || !txt.accounts) {
return fn(null, []);
}
//NOTE: this won't be accurate if there are
//multiple issuer accounts with different
//currencies associated with each.
var issuer = txt.accounts[0];
var currencies = [];
txt.currencies.forEach(function(currency) {
currencies.push({
issuer : issuer,
currency : Currency.from_json(currency),
domain : domain
});
});
fn(null, currencies);
});
};
exports.RippleTxt = RippleTxt;

View File

@@ -2,21 +2,21 @@
// Seed support
//
var sjcl = require('../../../build/sjcl');
var utils = require('./utils');
var jsbn = require('./jsbn');
var extend = require('extend');
var extend = require('extend');
var utils = require('./utils');
var sjcl = utils.sjcl;
var BigInteger = jsbn.BigInteger;
var BigInteger = utils.jsbn.BigInteger;
var Base = require('./base').Base,
UInt = require('./uint').UInt,
UInt256 = require('./uint256').UInt256,
KeyPair = require('./keypair').KeyPair;
var Base = require('./base').Base;
var UInt = require('./uint').UInt;
var UInt256 = require('./uint256').UInt256;
var UInt160 = require('./uint160').UInt160;
var KeyPair = require('./keypair').KeyPair;
var Seed = extend(function () {
// Internal form: NaN or BigInteger
this._curve = sjcl.ecc.curves['c256'];
this._curve = sjcl.ecc.curves.c256;
this._value = NaN;
}, UInt);
@@ -27,11 +27,11 @@ Seed.prototype.constructor = Seed;
// value = NaN on error.
// One day this will support rfc1751 too.
Seed.prototype.parse_json = function (j) {
if ('string' === typeof j) {
if (typeof j === 'string') {
if (!j.length) {
this._value = NaN;
// XXX Should actually always try and continue if it failed.
} else if (j[0] === "s") {
} else if (j[0] === 's') {
this._value = Base.decode_check(Base.VER_FAMILY_SEED, j);
} else if (j.length === 32) {
this._value = this.parse_hex(j);
@@ -47,8 +47,8 @@ Seed.prototype.parse_json = function (j) {
};
Seed.prototype.parse_passphrase = function (j) {
if ("string" !== typeof j) {
throw new Error("Passphrase must be a string");
if (typeof j !== 'string') {
throw new Error('Passphrase must be a string');
}
var hash = sjcl.hash.sha512.hash(sjcl.codec.utf8String.toBits(j));
@@ -60,8 +60,9 @@ Seed.prototype.parse_passphrase = function (j) {
};
Seed.prototype.to_json = function () {
if (!(this._value instanceof BigInteger))
if (!(this._value instanceof BigInteger)) {
return NaN;
}
var output = Base.encode_check(Base.VER_FAMILY_SEED, this.to_bytes());
@@ -70,30 +71,47 @@ Seed.prototype.to_json = function () {
function append_int(a, i) {
return [].concat(a, i >> 24, (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff);
}
};
function firstHalfOfSHA512(bytes) {
return sjcl.bitArray.bitSlice(
sjcl.hash.sha512.hash(sjcl.codec.bytes.toBits(bytes)),
0, 256
);
}
};
function SHA256_RIPEMD160(bits) {
return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
}
};
/**
* @param account
* {undefined} take first, default, KeyPair
*
* {Number} specifies the account number of the KeyPair
* desired.
*
* {Uint160} (from_json able), specifies the address matching the KeyPair
* that is desired.
*/
Seed.prototype.get_key = function (account) {
var account_number = 0, address;
Seed.prototype.get_key = function (account_id) {
if (!this.is_valid()) {
throw new Error("Cannot generate keys from invalid seed!");
throw new Error('Cannot generate keys from invalid seed!');
}
if (account) {
if (typeof account === 'number') {
account_number = account;
} else {
address = UInt160.from_json(account);
}
}
// XXX Should loop over keys until we find the right one
var private_gen, public_gen;
var curve = this._curve;
var i = 0;
var seq = 0;
var private_gen, public_gen, i = 0;
do {
private_gen = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(this.to_bytes(), i)));
i++;
@@ -102,15 +120,30 @@ Seed.prototype.get_key = function (account_id) {
public_gen = curve.G.mult(private_gen);
var sec;
i = 0;
var key_pair;
var max_loops = 1000; // TODO
do {
sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), seq), i)));
i++;
} while (!curve.r.greaterEquals(sec));
i = 0;
sec = sec.add(private_gen).mod(curve.r);
do {
sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), account_number), i)));
i++;
} while (!curve.r.greaterEquals(sec));
return KeyPair.from_bn_secret(sec);
account_number++;
sec = sec.add(private_gen).mod(curve.r);
key_pair = KeyPair.from_bn_secret(sec);
if (--max_loops <= 0) {
// We are almost certainly looking for an account that would take same
// value of $too_long {forever, ...}
throw new Error('Too many loops looking for KeyPair yielding '+
address.to_json() +' from ' + this.to_json());
};
} while (address && !key_pair.get_address().equals(address));
return key_pair;
};
exports.Seed = Seed;

View File

@@ -1,144 +1,330 @@
var binformat = require('./binformat'),
sjcl = require('../../../build/sjcl'),
extend = require('extend'),
stypes = require('./serializedtypes');
var assert = require('assert');
var extend = require('extend');
var binformat = require('./binformat');
var stypes = require('./serializedtypes');
var UInt256 = require('./uint256').UInt256;
var Crypt = require('./crypt').Crypt;
var utils = require('./utils');
var UInt256 = require('./uint256').UInt256;
var sjcl = utils.sjcl;
var BigInteger = utils.jsbn.BigInteger;
var SerializedObject = function () {
this.buffer = [];
var TRANSACTION_TYPES = { };
Object.keys(binformat.tx).forEach(function(key) {
TRANSACTION_TYPES[binformat.tx[key][0]] = key;
});
var LEDGER_ENTRY_TYPES = {};
Object.keys(binformat.ledger).forEach(function(key) {
LEDGER_ENTRY_TYPES[binformat.ledger[key][0]] = key;
});
var TRANSACTION_RESULTS = {};
Object.keys(binformat.ter).forEach(function(key) {
TRANSACTION_RESULTS[binformat.ter[key]] = key;
});
function SerializedObject(buf) {
if (Array.isArray(buf) || (Buffer && Buffer.isBuffer(buf)) ) {
this.buffer = buf;
} else if (typeof buf === 'string') {
this.buffer = sjcl.codec.bytes.fromBits(sjcl.codec.hex.toBits(buf));
} else if (!buf) {
this.buffer = [];
} else {
throw new Error('Invalid buffer passed.');
}
this.pointer = 0;
};
SerializedObject.from_json = function (obj) {
var typedef;
var so = new SerializedObject();
SerializedObject.from_json = function(obj) {
// Create a copy of the object so we don't modify it
obj = extend({}, obj);
var obj = extend({}, obj);
var so = new SerializedObject();
var typedef;
if ("number" === typeof obj.TransactionType) {
if (typeof obj.TransactionType === 'number') {
obj.TransactionType = SerializedObject.lookup_type_tx(obj.TransactionType);
if (!obj.TransactionType) {
throw new Error("Transaction type ID is invalid.");
throw new Error('Transaction type ID is invalid.');
}
}
if ("string" === typeof obj.TransactionType) {
typedef = binformat.tx[obj.TransactionType].slice();
if (typeof obj.LedgerEntryType === 'number') {
obj.LedgerEntryType = SerializedObject.lookup_type_le(obj.LedgerEntryType);
if (!obj.LedgerEntryType) {
throw new Error('LedgerEntryType ID is invalid.');
}
}
if (typeof obj.TransactionType === 'string') {
typedef = binformat.tx[obj.TransactionType];
if (!Array.isArray(typedef)) {
throw new Error('Transaction type is invalid');
}
typedef = typedef.slice();
obj.TransactionType = typedef.shift();
} else if ("undefined" !== typeof obj.LedgerEntryType) {
// XXX: TODO
throw new Error("Ledger entry binary format not yet implemented.");
} else throw new Error("Object to be serialized must contain either " +
"TransactionType or LedgerEntryType.");
} else if (typeof obj.LedgerEntryType === 'string') {
typedef = binformat.ledger[obj.LedgerEntryType];
if (!Array.isArray(typedef)) {
throw new Error('LedgerEntryType is invalid');
}
typedef = typedef.slice();
obj.LedgerEntryType = typedef.shift();
} else if (typeof obj.AffectedNodes === 'object') {
typedef = binformat.metadata;
} else {
throw new Error('Object to be serialized must contain either' +
' TransactionType, LedgerEntryType or AffectedNodes.');
}
// ND: This from_*json* seems a reasonable place to put validation of `json`
SerializedObject.check_no_missing_fields(typedef, obj);
so.serialize(typedef, obj);
return so;
};
SerializedObject.prototype.append = function (bytes) {
SerializedObject.check_no_missing_fields = function(typedef, obj) {
var missing_fields = [];
for (var i = typedef.length - 1; i >= 0; i--) {
var spec = typedef[i];
var field = spec[0];
var requirement = spec[1];
if (binformat.REQUIRED === requirement && obj[field] === void(0)) {
missing_fields.push(field);
};
};
if (missing_fields.length > 0) {
var object_name;
if (obj.TransactionType !== void(0)) {
object_name = SerializedObject.lookup_type_tx(obj.TransactionType);
} else if (obj.LedgerEntryType != null){
object_name = SerializedObject.lookup_type_le(obj.LedgerEntryType);
} else {
object_name = "TransactionMetaData";
}
throw new Error(object_name + " is missing fields: " +
JSON.stringify(missing_fields));
};
};
SerializedObject.prototype.append = function(bytes) {
if (bytes instanceof SerializedObject) {
bytes = bytes.buffer;
}
this.buffer = this.buffer.concat(bytes);
this.pointer += bytes.length;
};
SerializedObject.prototype.to_bits = function ()
{
SerializedObject.prototype.resetPointer = function() {
this.pointer = 0;
};
function readOrPeek(advance) {
return function(bytes) {
var start = this.pointer;
var end = start + bytes;
if (end > this.buffer.length) {
throw new Error('Buffer length exceeded');
}
var result = this.buffer.slice(start, end);
if (advance) {
this.pointer = end;
}
return result;
};
};
SerializedObject.prototype.read = readOrPeek(true);
SerializedObject.prototype.peek = readOrPeek(false);
SerializedObject.prototype.to_bits = function() {
return sjcl.codec.bytes.toBits(this.buffer);
};
SerializedObject.prototype.to_hex = function () {
SerializedObject.prototype.to_hex = function() {
return sjcl.codec.hex.fromBits(this.to_bits()).toUpperCase();
};
SerializedObject.prototype.serialize = function (typedef, obj)
{
SerializedObject.prototype.to_json = function() {
var old_pointer = this.pointer;
this.resetPointer();
var output = { };
while (this.pointer < this.buffer.length) {
var key_and_value = stypes.parse(this);
var key = key_and_value[0];
var value = key_and_value[1];
output[key] = SerializedObject.jsonify_structure(value, key);
}
this.pointer = old_pointer;
return output;
};
SerializedObject.jsonify_structure = function(structure, field_name) {
var output;
switch (typeof structure) {
case 'number':
switch (field_name) {
case 'LedgerEntryType':
output = LEDGER_ENTRY_TYPES[structure];
break;
case 'TransactionResult':
output = TRANSACTION_RESULTS[structure];
break;
case 'TransactionType':
output = TRANSACTION_TYPES[structure];
break;
default:
output = structure;
}
break;
case 'object':
if (structure === null) {
break;
}
if (typeof structure.to_json === 'function') {
output = structure.to_json();
} else if (structure instanceof BigInteger) {
output = structure.toString(16).toUpperCase();
} else {
//new Array or Object
output = new structure.constructor();
var keys = Object.keys(structure);
for (var i=0, l=keys.length; i<l; i++) {
var key = keys[i];
output[key] = SerializedObject.jsonify_structure(structure[key], key);
}
}
break;
default:
output = structure;
}
return output;
};
SerializedObject.prototype.serialize = function(typedef, obj) {
// Serialize object without end marker
stypes.Object.serialize(this, obj, true);
// ST: Old serialization
/*
// Ensure canonical order
typedef = SerializedObject._sort_typedef(typedef.slice());
typedef = SerializedObject.sort_typedef(typedef);
// Serialize fields
for (var i = 0, l = typedef.length; i < l; i++) {
var spec = typedef[i];
this.serialize_field(spec, obj);
for (var i=0, l=typedef.length; i<l; i++) {
this.serialize_field(typedef[i], obj);
}
*/
};
SerializedObject.prototype.signing_hash = function (prefix)
{
SerializedObject.prototype.hash = function(prefix) {
var sign_buffer = new SerializedObject();
stypes.Int32.serialize(sign_buffer, prefix);
// Add hashing prefix
if ("undefined" !== typeof prefix) {
stypes.Int32.serialize(sign_buffer, prefix);
}
// Copy buffer to temporary buffer
sign_buffer.append(this.buffer);
return sign_buffer.hash_sha512_half();
// XXX We need a proper Buffer class then Crypt could accept that
var bits = sjcl.codec.bytes.toBits(sign_buffer.buffer);
return Crypt.hashSha512Half(bits);
};
SerializedObject.prototype.hash_sha512_half = function ()
{
var bits = sjcl.codec.bytes.toBits(this.buffer),
hash = sjcl.bitArray.bitSlice(sjcl.hash.sha512.hash(bits), 0, 256);
// DEPRECATED
SerializedObject.prototype.signing_hash = SerializedObject.prototype.hash;
return UInt256.from_hex(sjcl.codec.hex.fromBits(hash));
};
SerializedObject.prototype.serialize_field = function (spec, obj)
{
spec = spec.slice();
var name = spec.shift(),
presence = spec.shift(),
field_id = spec.shift(),
Type = spec.shift();
if ("undefined" !== typeof obj[name]) {
//console.log(name, Type.id, field_id);
this.append(SerializedObject.get_field_header(Type.id, field_id));
SerializedObject.prototype.serialize_field = function(spec, obj) {
var name = spec[0];
var presence = spec[1];
var field_id = spec[2];
var Type = stypes[spec[3]];
if (typeof obj[name] !== 'undefined') {
// ST: Old serialization code
//this.append(SerializedObject.get_field_header(Type.id, field_id));
try {
Type.serialize(this, obj[name]);
// ST: Old serialization code
//Type.serialize(this, obj[name]);
stypes.serialize(this, name, obj[name]);
} catch (e) {
// Add field name to message and rethrow
e.message = "Error serializing '"+name+"': "+e.message;
e.message = 'Error serializing "' + name + '": ' + e.message;
throw e;
}
} else if (presence === binformat.REQUIRED) {
throw new Error('Missing required field '+name);
throw new Error('Missing required field ' + name);
}
};
SerializedObject.get_field_header = function (type_id, field_id)
{
var buffer = [0];
if (type_id > 0xf) buffer.push(type_id & 0xff);
else buffer[0] += (type_id & 0xf) << 4;
SerializedObject.get_field_header = function(type_id, field_id) {
var buffer = [ 0 ];
if (field_id > 0xf) buffer.push(field_id & 0xff);
else buffer[0] += field_id & 0xf;
if (type_id > 0xF) {
buffer.push(type_id & 0xFF);
} else {
buffer[0] += (type_id & 0xF) << 4;
}
if (field_id > 0xF) {
buffer.push(field_id & 0xFF);
} else {
buffer[0] += field_id & 0xF;
}
return buffer;
};
function sort_field_compare(a, b) {
// Sort by type id first, then by field id
return a[3].id !== b[3].id ?
a[3].id - b[3].id :
a[2] - b[2];
};
SerializedObject._sort_typedef = function (typedef) {
SerializedObject.sort_typedef = function(typedef) {
assert(Array.isArray(typedef));
function sort_field_compare(a, b) {
// Sort by type id first, then by field id
return a[3] !== b[3] ? stypes[a[3]].id - stypes[b[3]].id : a[2] - b[2];
};
return typedef.sort(sort_field_compare);
};
SerializedObject.lookup_type_tx = function (id) {
for (var i in binformat.tx) {
if (!binformat.tx.hasOwnProperty(i)) continue;
SerializedObject.lookup_type_tx = function(id) {
assert.strictEqual(typeof id, 'number');
return TRANSACTION_TYPES[id];
};
if (binformat.tx[i][0] === id) {
return i;
}
}
return null;
SerializedObject.lookup_type_le = function (id) {
assert(typeof id === 'number');
return LEDGER_ENTRY_TYPES[id];
};
exports.SerializedObject = SerializedObject;

View File

@@ -6,154 +6,297 @@
* SerializedObject.parse() or SerializedObject.serialize().
*/
var extend = require('extend'),
utils = require('./utils'),
sjcl = require('../../../build/sjcl');
var assert = require('assert');
var extend = require('extend');
var binformat = require('./binformat');
var utils = require('./utils');
var sjcl = utils.sjcl;
var amount = require('./amount'),
UInt160 = amount.UInt160,
UInt256 = require('./uint256').UInt256,
Amount = amount.Amount,
Currency= amount.Currency;
var UInt128 = require('./uint128').UInt128;
var UInt160 = require('./uint160').UInt160;
var UInt256 = require('./uint256').UInt256;
var Base = require('./base').Base;
var amount = require('./amount');
var Amount = amount.Amount;
var Currency = amount.Currency;
// Shortcuts
var hex = sjcl.codec.hex,
bytes = sjcl.codec.bytes;
var hex = sjcl.codec.hex;
var bytes = sjcl.codec.bytes;
var BigInteger = utils.jsbn.BigInteger;
var SerializedType = function (methods) {
extend(this, methods);
};
SerializedType.prototype.serialize_hex = function (so, hexData) {
function isNumber(val) {
return typeof val === 'number' && isFinite(val);
};
function isString(val) {
return typeof val === 'string';
};
function isHexInt64String(val) {
return isString(val) && /^[0-9A-F]{0,16}$/i.test(val);
};
function isCurrencyString(val) {
return isString(val) && /^[A-Z0-9]{3}$/.test(val);
};
function isBigInteger(val) {
return val instanceof BigInteger;
};
function serialize_hex(so, hexData, noLength) {
var byteData = bytes.fromBits(hex.toBits(hexData));
this.serialize_varint(so, byteData.length);
if (!noLength) {
SerializedType.serialize_varint(so, byteData.length);
}
so.append(byteData);
};
SerializedType.prototype.serialize_varint = function (so, val) {
/**
* parses bytes as hex
*/
function convert_bytes_to_hex (byte_array) {
return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(byte_array)).toUpperCase();
};
SerializedType.serialize_varint = function (so, val) {
if (val < 0) {
throw new Error("Variable integers are unsigned.");
throw new Error('Variable integers are unsigned.');
}
if (val <= 192) {
so.append([val]);
} else if (val <= 12,480) {
} else if (val <= 12480) {
val -= 193;
so.append([193 + (val >>> 8), val & 0xff]);
} else if (val <= 918744) {
val -= 12481;
so.append([
241 + (val >>> 16),
val >>> 8 & 0xff,
val & 0xff
]);
} else throw new Error("Variable integer overflow.");
so.append([ 241 + (val >>> 16), val >>> 8 & 0xff, val & 0xff ]);
} else {
throw new Error('Variable integer overflow.');
}
};
SerializedType.prototype.parse_varint = function (so) {
var b1 = so.read(1)[0], b2, b3;
var result;
if (b1 > 254) {
throw new Error('Invalid varint length indicator');
}
if (b1 <= 192) {
result = b1;
} else if (b1 <= 240) {
b2 = so.read(1)[0];
result = 193 + (b1 - 193) * 256 + b2;
} else if (b1 <= 254) {
b2 = so.read(1)[0];
b3 = so.read(1)[0];
result = 12481 + (b1 - 241) * 65536 + b2 * 256 + b3;
}
return result;
};
// In the following, we assume that the inputs are in the proper range. Is this correct?
// Helper functions for 1-, 2-, and 4-byte integers.
/**
* Convert an integer value into an array of bytes.
*
* The result is appended to the serialized object ('so').
*/
function append_byte_array(so, val, bytes) {
if (!isNumber(val)) {
throw new Error('Value is not a number');
}
if (val < 0 || val >= Math.pow(256, bytes)) {
throw new Error('Value out of bounds');
}
var newBytes = [ ];
for (var i=0; i<bytes; i++) {
newBytes.unshift(val >>> (i * 8) & 0xff);
}
so.append(newBytes);
};
// Convert a certain number of bytes from the serialized object ('so') into an integer.
function readAndSum(so, bytes) {
var sum = 0;
if (bytes > 4) {
throw new Error('This function only supports up to four bytes.');
}
for (var i=0; i<bytes; i++) {
var byte = so.read(1)[0];
sum += (byte << (8 * (bytes - i - 1)));
}
// Convert to unsigned integer
return sum >>> 0;
};
var STInt8 = exports.Int8 = new SerializedType({
serialize: function (so, val) {
so.append([val & 0xff]);
append_byte_array(so, val, 1);
},
parse: function (so) {
return so.read(1)[0];
return readAndSum(so, 1);
}
});
STInt8.id = 16;
var STInt16 = exports.Int16 = new SerializedType({
serialize: function (so, val) {
so.append([
val >>> 8 & 0xff,
val & 0xff
]);
append_byte_array(so, val, 2);
},
parse: function (so) {
// XXX
throw new Error("Parsing Int16 not implemented");
return readAndSum(so, 2);
}
});
STInt16.id = 1;
var STInt32 = exports.Int32 = new SerializedType({
serialize: function (so, val) {
so.append([
val >>> 24 & 0xff,
val >>> 16 & 0xff,
val >>> 8 & 0xff,
val & 0xff
]);
append_byte_array(so, val, 4);
},
parse: function (so) {
// XXX
throw new Error("Parsing Int32 not implemented");
return readAndSum(so, 4);
}
});
STInt32.id = 2;
var STInt64 = exports.Int64 = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Int64 not implemented");
var bigNumObject;
if (isNumber(val)) {
val = Math.floor(val);
if (val < 0) {
throw new Error('Negative value for unsigned Int64 is invalid.');
}
bigNumObject = new BigInteger(String(val), 10);
} else if (isString(val)) {
if (!isHexInt64String(val)) {
throw new Error('Not a valid hex Int64.');
}
bigNumObject = new BigInteger(val, 16);
} else if (isBigInteger(val)) {
if (val.compareTo(BigInteger.ZERO) < 0) {
throw new Error('Negative value for unsigned Int64 is invalid.');
}
bigNumObject = val;
} else {
throw new Error('Invalid type for Int64');
}
var hex = bigNumObject.toString(16);
if (hex.length > 16) {
throw new Error('Int64 is too large');
}
while (hex.length < 16) {
hex = '0' + hex;
}
serialize_hex(so, hex, true); //noLength = true
},
parse: function (so) {
// XXX
throw new Error("Parsing Int64 not implemented");
var bytes = so.read(8);
// We need to add a 0, so if the high bit is set it won't think it's a
// pessimistic numeric fraek. What doth lief?
var result = new BigInteger([0].concat(bytes), 256);
assert(result instanceof BigInteger);
return result;
}
});
STInt64.id = 3;
var STHash128 = exports.Hash128 = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Hash128 not implemented");
var hash = UInt128.from_json(val);
if (!hash.is_valid()) {
throw new Error('Invalid Hash128');
}
serialize_hex(so, hash.to_hex(), true); //noLength = true
},
parse: function (so) {
// XXX
throw new Error("Parsing Hash128 not implemented");
return UInt128.from_bytes(so.read(16));
}
});
STHash128.id = 4;
var STHash256 = exports.Hash256 = new SerializedType({
serialize: function (so, val) {
var hash = UInt256.from_json(val);
this.serialize_hex(so, hash.to_hex());
if (!hash.is_valid()) {
throw new Error('Invalid Hash256');
}
serialize_hex(so, hash.to_hex(), true); //noLength = true
},
parse: function (so) {
// XXX
throw new Error("Parsing Hash256 not implemented");
return UInt256.from_bytes(so.read(32));
}
});
STHash256.id = 5;
var STHash160 = exports.Hash160 = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Hash160 not implemented");
var hash = UInt160.from_json(val);
if (!hash.is_valid()) {
throw new Error('Invalid Hash160');
}
serialize_hex(so, hash.to_hex(), true); //noLength = true
},
parse: function (so) {
// XXX
throw new Error("Parsing Hash160 not implemented");
return UInt160.from_bytes(so.read(20));
}
});
STHash160.id = 17;
// Internal
var STCurrency = new SerializedType({
serialize: function (so, val) {
var currency = val.to_json();
if ("string" === typeof currency && currency.length === 3) {
var currencyCode = currency.toUpperCase(),
currencyData = utils.arraySet(20, 0);
serialize: function (so, val, xrp_as_ascii) {
var currencyData = val.to_bytes();
if (!/^[A-Z]{3}$/.test(currencyCode)) {
throw new Error('Invalid currency code');
}
currencyData[12] = currencyCode.charCodeAt(0) & 0xff;
currencyData[13] = currencyCode.charCodeAt(1) & 0xff;
currencyData[14] = currencyCode.charCodeAt(2) & 0xff;
so.append(currencyData);
} else {
if (!currencyData) {
throw new Error('Tried to serialize invalid/unimplemented currency type.');
}
so.append(currencyData);
},
parse: function (so) {
// XXX
throw new Error("Parsing Currency not implemented");
var bytes = so.read(20);
var currency = Currency.from_bytes(bytes);
// XXX Disabled check. Theoretically, the Currency class should support any
// UInt160 value and consider it valid. But it doesn't, so for the
// deserialization to be usable, we need to allow invalid results for now.
//if (!currency.is_valid()) {
// throw new Error('Invalid currency: '+convert_bytes_to_hex(bytes));
//}
return currency;
}
});
@@ -161,11 +304,12 @@ var STAmount = exports.Amount = new SerializedType({
serialize: function (so, val) {
var amount = Amount.from_json(val);
if (!amount.is_valid()) {
throw new Error("Not a valid Amount object.");
throw new Error('Not a valid Amount object.');
}
// Amount (64-bit integer)
var valueBytes = utils.arraySet(8, 0);
if (amount.is_native()) {
var valueHex = amount._value.toString(16);
@@ -173,8 +317,9 @@ var STAmount = exports.Amount = new SerializedType({
if (valueHex.length > 16) {
throw new Error('Value out of bounds');
}
while (valueHex.length < 16) {
valueHex = "0" + valueHex;
valueHex = '0' + valueHex;
}
valueBytes = bytes.fromBits(hex.toBits(valueHex));
@@ -182,7 +327,10 @@ var STAmount = exports.Amount = new SerializedType({
// Amount enforces the range correctly, but we'll clear them anyway just
// so this code can make certain guarantees about the encoded value.
valueBytes[0] &= 0x3f;
if (!amount.is_negative()) valueBytes[0] |= 0x40;
if (!amount.is_negative()) {
valueBytes[0] |= 0x40;
}
} else {
var hi = 0, lo = 0;
@@ -191,11 +339,12 @@ var STAmount = exports.Amount = new SerializedType({
if (!amount.is_zero()) {
// Second bit: non-negative?
if (!amount.is_negative()) hi |= 1 << 30;
if (!amount.is_negative()) {
hi |= 1 << 30;
}
// Next eight bits: offset/exponent
hi |= ((97 + amount._offset) & 0xff) << 22;
// Remaining 52 bits: mantissa
hi |= amount._value.shiftRight(32).intValue() & 0x3fffff;
lo = amount._value.intValue() & 0xffffffff;
@@ -209,112 +358,392 @@ var STAmount = exports.Amount = new SerializedType({
if (!amount.is_native()) {
// Currency (160-bit hash)
var currency = amount.currency();
STCurrency.serialize(so, currency);
STCurrency.serialize(so, currency, true);
// Issuer (160-bit hash)
so.append(amount.issuer().to_bytes());
}
},
parse: function (so) {
// XXX
throw new Error("Parsing Amount not implemented");
var amount = new Amount();
var value_bytes = so.read(8);
var is_zero = !(value_bytes[0] & 0x7f);
for (var i=1; i<8; i++) {
is_zero = is_zero && !value_bytes[i];
}
if (value_bytes[0] & 0x80) {
//non-native
var currency = STCurrency.parse(so);
var issuer_bytes = so.read(20);
var issuer = UInt160.from_bytes(issuer_bytes);
issuer.set_version(Base.VER_ACCOUNT_ID);
var offset = ((value_bytes[0] & 0x3f) << 2) + (value_bytes[1] >>> 6) - 97;
var mantissa_bytes = value_bytes.slice(1);
mantissa_bytes[0] &= 0x3f;
var value = new BigInteger(mantissa_bytes, 256);
if (value.equals(BigInteger.ZERO) && !is_zero ) {
throw new Error('Invalid zero representation');
}
amount._value = value;
amount._offset = offset;
amount._currency = currency;
amount._issuer = issuer;
amount._is_native = false;
} else {
//native
var integer_bytes = value_bytes.slice();
integer_bytes[0] &= 0x3f;
amount._value = new BigInteger(integer_bytes, 256);
amount._is_native = true;
}
amount._is_negative = !is_zero && !(value_bytes[0] & 0x40);
return amount;
}
});
var STVL = exports.VariableLength = new SerializedType({
STAmount.id = 6;
var STVL = exports.VariableLength = exports.VL = new SerializedType({
serialize: function (so, val) {
if ("string" === typeof val) this.serialize_hex(so, val);
else throw new Error("Unknown datatype.");
if (typeof val === 'string') {
serialize_hex(so, val);
} else {
throw new Error('Unknown datatype.');
}
},
parse: function (so) {
// XXX
throw new Error("Parsing VL not implemented");
var len = this.parse_varint(so);
return convert_bytes_to_hex(so.read(len));
}
});
STVL.id = 7;
var STAccount = exports.Account = new SerializedType({
serialize: function (so, val) {
var account = UInt160.from_json(val);
this.serialize_hex(so, account.to_hex());
if (!account.is_valid()) {
throw new Error('Invalid account!');
}
serialize_hex(so, account.to_hex());
},
parse: function (so) {
// XXX
throw new Error("Parsing Account not implemented");
var len = this.parse_varint(so);
if (len !== 20) {
throw new Error('Non-standard-length account ID');
}
var result = UInt160.from_bytes(so.read(len));
result.set_version(Base.VER_ACCOUNT_ID);
//console.log('PARSED 160:', result.to_json());
if (false && !result.is_valid()) {
throw new Error('Invalid Account');
}
return result;
}
});
STAccount.id = 8;
var STPathSet = exports.PathSet = new SerializedType({
typeBoundary: 0xff,
typeEnd: 0x00,
typeAccount: 0x01,
typeCurrency: 0x10,
typeIssuer: 0x20,
typeBoundary: 0xff,
typeEnd: 0x00,
typeAccount: 0x01,
typeCurrency: 0x10,
typeIssuer: 0x20,
serialize: function (so, val) {
// XXX
for (var i = 0, l = val.length; i < l; i++) {
for (var i=0, l=val.length; i<l; i++) {
// Boundary
if (i) STInt8.serialize(so, this.typeBoundary);
if (i) {
STInt8.serialize(so, this.typeBoundary);
}
for (var j = 0, l2 = val[i].length; j < l2; j++) {
for (var j=0, l2=val[i].length; j<l2; j++) {
var entry = val[i][j];
//if (entry.hasOwnProperty('_value')) {entry = entry._value;}
var type = 0;
if (entry.account) type |= this.typeAccount;
if (entry.currency) type |= this.typeCurrency;
if (entry.issuer) type |= this.typeIssuer;
if (entry.account) {
type |= this.typeAccount;
}
if (entry.currency) {
type |= this.typeCurrency;
}
if (entry.issuer) {
type |= this.typeIssuer;
}
STInt8.serialize(so, type);
if (entry.account) {
so.append(UInt160.from_json(entry.account).to_bytes());
}
if (entry.currency) {
var currency = Currency.from_json(entry.currency);
var currency = Currency.from_json(entry.currency, entry.non_native);
STCurrency.serialize(so, currency);
}
if (entry.issuer) {
so.append(UInt160.from_json(entry.issuer).to_bytes());
}
}
}
STInt8.serialize(so, this.typeEnd);
},
parse: function (so) {
// XXX
throw new Error("Parsing PathSet not implemented");
// should return a list of lists:
/*
[
[entry, entry],
[entry, entry, entry],
[entry],
[]
]
each entry has one or more of the following attributes: amount, currency, issuer.
*/
var path_list = [];
var current_path = [];
var tag_byte;
while ((tag_byte = so.read(1)[0]) !== this.typeEnd) {
//TODO: try/catch this loop, and catch when we run out of data without reaching the end of the data structure.
//Now determine: is this an end, boundary, or entry-begin-tag?
//console.log('Tag byte:', tag_byte);
if (tag_byte === this.typeBoundary) {
//console.log('Boundary');
if (current_path) { //close the current path, if there is one,
path_list.push(current_path);
}
current_path = [ ]; //and start a new one.
continue;
}
//It's an entry-begin tag.
//console.log('It's an entry-begin tag.');
var entry = {};
if (tag_byte & this.typeAccount) {
//console.log('entry.account');
/*var bta = so.read(20);
console.log('BTA:', bta);*/
entry.account = STHash160.parse(so);
entry.account.set_version(Base.VER_ACCOUNT_ID);
}
if (tag_byte & this.typeCurrency) {
//console.log('entry.currency');
entry.currency = STCurrency.parse(so);
if (entry.currency.to_json() === 'XRP' && !entry.currency.is_native()) {
entry.non_native = true;
}
}
if (tag_byte & this.typeIssuer) {
//console.log('entry.issuer');
entry.issuer = STHash160.parse(so);
// Enable and set correct type of base-58 encoding
entry.issuer.set_version(Base.VER_ACCOUNT_ID);
//console.log('DONE WITH ISSUER!');
}
if (entry.account || entry.currency || entry.issuer) {
current_path.push(entry);
} else {
throw new Error('Invalid path entry'); //It must have at least something in it.
}
}
if (current_path) {
//close the current path, if there is one,
path_list.push(current_path);
}
return path_list;
}
});
STPathSet.id = 18;
var STVector256 = exports.Vector256 = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Vector256 not implemented");
serialize: function (so, val) { //Assume val is an array of STHash256 objects.
var length_as_varint = SerializedType.serialize_varint(so, val.length * 32);
for (var i=0, l=val.length; i<l; i++) {
STHash256.serialize(so, val[i]);
}
},
parse: function (so) {
// XXX
throw new Error("Parsing Vector256 not implemented");
var length = this.parse_varint(so);
var output = [];
// length is number of bytes not number of Hash256
for (var i=0; i<length / 32; i++) {
output.push(STHash256.parse(so));
}
return output;
}
});
STVector256.id = 19;
exports.serialize = exports.serialize_whatever = serialize;
function serialize(so, field_name, value) {
//so: a byte-stream to serialize into.
//field_name: a string for the field name ('LedgerEntryType' etc.)
//value: the value of that field.
var field_coordinates = binformat.fieldsInverseMap[field_name];
var type_bits = field_coordinates[0];
var field_bits = field_coordinates[1];
var tag_byte = (type_bits < 16 ? type_bits << 4 : 0) | (field_bits < 16 ? field_bits : 0);
if (field_name === 'LedgerEntryType' && 'string' === typeof value) {
value = binformat.ledger[value][0];
}
if (field_name === 'TransactionResult' && 'string' === typeof value) {
value = binformat.ter[value];
}
STInt8.serialize(so, tag_byte);
if (type_bits >= 16) {
STInt8.serialize(so, type_bits);
}
if (field_bits >= 16) {
STInt8.serialize(so, field_bits);
}
// Get the serializer class (ST...) for a field based on the type bits.
var serialized_object_type = exports[binformat.types[type_bits]];
//do something with val[keys] and val[keys[i]];
serialized_object_type.serialize(so, value);
}
//Take the serialized object, figure out what type/field it is, and return the parsing of that.
exports.parse = exports.parse_whatever = parse;
function parse(so) {
var tag_byte = so.read(1)[0];
var type_bits = tag_byte >> 4;
if (type_bits === 0) {
type_bits = so.read(1)[0];
}
// Get the parser class (ST...) for a field based on the type bits.
var type = exports[binformat.types[type_bits]];
assert(type, 'Unknown type - header byte is 0x' + tag_byte.toString(16));
var field_bits = tag_byte & 0x0f;
var field_name = (field_bits === 0)
? field_name = binformat.fields[type_bits][so.read(1)[0]]
: field_name = binformat.fields[type_bits][field_bits];
assert(field_name, 'Unknown field - header byte is 0x' + tag_byte.toString(16));
return [ field_name, type.parse(so) ]; //key, value
};
function sort_fields(keys) {
function sort_field_compare(a, b) {
var a_field_coordinates = binformat.fieldsInverseMap[a];
var a_type_bits = a_field_coordinates[0];
var a_field_bits = a_field_coordinates[1];
var b_field_coordinates = binformat.fieldsInverseMap[b];
var b_type_bits = b_field_coordinates[0];
var b_field_bits = b_field_coordinates[1];
// Sort by type id first, then by field id
return a_type_bits !== b_type_bits ? a_type_bits - b_type_bits : a_field_bits - b_field_bits;
};
return keys.sort(sort_field_compare);
}
var STObject = exports.Object = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Object not implemented");
serialize: function (so, val, no_marker) {
var keys = Object.keys(val);
// Ignore lowercase field names - they're non-serializable fields by
// convention.
keys = keys.filter(function (key) {
return key[0] !== key[0].toLowerCase();
});
keys.forEach(function (key) {
if (typeof binformat.fieldsInverseMap[key] === 'undefined') {
throw new Error('JSON contains unknown field: "' + key + '"');
}
});
// Sort fields
keys = sort_fields(keys);
for (var i=0; i<keys.length; i++) {
serialize(so, keys[i], val[keys[i]]);
}
if (!no_marker) {
//Object ending marker
STInt8.serialize(so, 0xe1);
}
},
parse: function (so) {
// XXX
throw new Error("Parsing Object not implemented");
var output = {};
while (so.peek(1)[0] !== 0xe1) {
var keyval = parse(so);
output[keyval[0]] = keyval[1];
}
so.read(1);
return output;
}
});
STObject.id = 14;
var STArray = exports.Array = new SerializedType({
serialize: function (so, val) {
// XXX
throw new Error("Serializing Array not implemented");
for (var i=0, l=val.length; i<l; i++) {
var keys = Object.keys(val[i]);
if (keys.length !== 1) {
throw Error('Cannot serialize an array containing non-single-key objects');
}
var field_name = keys[0];
var value = val[i][field_name];
serialize(so, field_name, value);
}
//Array ending marker
STInt8.serialize(so, 0xf1);
},
parse: function (so) {
// XXX
throw new Error("Parsing Array not implemented");
var output = [ ];
while (so.peek(1)[0] !== 0xf1) {
var keyval = parse(so);
var obj = { };
obj[keyval[0]] = keyval[1];
output.push(obj);
}
so.read(1);
return output;
}
});
STArray.id = 15;

View File

@@ -1,282 +1,752 @@
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('./utils');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var Amount = require('./amount').Amount;
var Transaction = require('./transaction').Transaction;
var log = require('./log').internal.sub('server');
/**
* @constructor Server
* @param remote The Remote object
* @param cfg Configuration parameters.
*
* Keys for cfg:
* url
*/
* @param {Remote} Reference to a Remote object
* @param {Object} Options
* @param {String} host
* @param {Number|String} port
* @param [Boolean] securec
*/
var Server = function (remote, opts) {
function Server(remote, opts) {
EventEmitter.call(this);
if (typeof opts !== 'object' || typeof opts.url !== 'string') {
throw new Error('Invalid server configuration.');
}
var self = this;
this._remote = remote;
this._opts = opts;
if (typeof opts === 'string') {
var parsedUrl = url.parse(opts);
opts = {
host: parsedUrl.hostname,
port: parsedUrl.port,
secure: (parsedUrl.protocol === 'ws:') ? false : true
};
}
this._ws = void(0);
this._connected = false;
this._should_connect = false;
this._state = void(0);
if (typeof opts !== 'object') {
throw new TypeError('Server configuration is not an Object');
}
this._id = 0;
this._retry = 0;
if (!Server.domainRE.test(opts.host)) {
throw new Error('Server host is malformed, use "host" and "port" server configuration');
}
this._requests = { };
// We want to allow integer strings as valid port numbers for backward compatibility
if (!(opts.port = Number(opts.port))) {
throw new TypeError('Server port must be a number');
}
this.on('message', function(message) {
self._handle_message(message);
if (opts.port < 1 || opts.port > 65535) {
throw new TypeError('Server "port" must be an integer in range 1-65535');
}
if (typeof opts.secure !== 'boolean') {
opts.secure = true;
}
this._remote = remote;
this._opts = opts;
this._ws = void(0);
this._connected = false;
this._shouldConnect = false;
this._state = 'offline';
this._id = 0;
this._retry = 0;
this._requests = { };
this._load_base = 256;
this._load_factor = 256;
this._fee = 10;
this._fee_ref = 10;
this._fee_base = 10;
this._reserve_base = void(0);
this._reserve_inc = void(0);
this._fee_cushion = this._remote.fee_cushion;
this._lastLedgerIndex = NaN;
this._lastLedgerClose = NaN;
this._score = 0;
this._scoreWeights = {
ledgerclose: 5,
response: 1
};
this._url = this._opts.url = (this._opts.secure ? 'wss://' : 'ws://')
+ this._opts.host + ':' + this._opts.port;
this.on('message', onMessage);
function onMessage(message) {
self._handleMessage(message);
};
this.on('response_subscribe', onSubscribeResponse);
function onSubscribeResponse(message) {
self._handleResponseSubscribe(message);
};
function setActivityInterval() {
var interval = self._checkActivity.bind(self);
self._activityInterval = setInterval(interval, 1000);
};
this.on('disconnect', function onDisconnect() {
clearInterval(self._activityInterval);
self.once('ledger_closed', setActivityInterval);
});
this.on('response_subscribe', function(message) {
self._handle_response_subscribe(message);
this.once('ledger_closed', setActivityInterval);
this._remote.on('ledger_closed', function(ledger) {
self._updateScore('ledgerclose', ledger);
});
this.on('response_ping', function(message, request) {
self._updateScore('response', request);
});
this.on('load_changed', function(load) {
self._updateScore('loadchange', load);
});
};
util.inherits(Server, EventEmitter);
Server.domainRE = /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?)*\.?$/;
/**
* Server states that we will treat as the server being online.
*
* Our requirements are that the server can process transactions and notify
* us of changes.
*/
Server.online_states = [
'syncing'
, 'tracking'
, 'proposing'
, 'validating'
, 'full'
Server.onlineStates = [
'syncing',
'tracking',
'proposing',
'validating',
'full'
];
Server.prototype._is_online = function (status) {
return Server.online_states.indexOf(status) !== -1;
/**
* This is the final interface between client code and a socket connection to a
* `rippled` server. As such, this is a decent hook point to allow a WebSocket
* interface conforming object to be used as a basis to mock rippled. This
* avoids the need to bind a websocket server to a port and allows a more
* synchronous style of code to represent a client <-> server message sequence.
* We can also use this to log a message sequence to a buffer.
*
* @api private
*/
Server.websocketConstructor = function() {
// We require this late, because websocket shims may be loaded after
// ripple-lib in the browser
return require('ws');
};
Server.prototype._set_state = function (state) {
if (state !== this._state) {
this._state = state;
/**
* Set server state
*
* @param {String} state
* @api private
*/
Server.prototype._setState = function(state) {
if (state !== this._state) {
if (this._remote.trace) {
log.info('set_state:', state);
}
this._state = state;
this.emit('state', state);
if (state === 'online') {
this._connected = true;
this.emit('connect');
} else if (state === 'offline') {
this._connected = false;
this.emit('disconnect');
switch (state) {
case 'online':
this._connected = true;
this.emit('connect');
break;
case 'offline':
this._connected = false;
this.emit('disconnect');
break;
}
}
};
Server.prototype.connect = function () {
/**
* Check that server is still active.
*
* Server activity is determined by ledger_closed events.
* Maximum delay to receive a ledger_closed event is 20s.
*
* If server is inactive, reconnect
*
* @api private
*/
Server.prototype._checkActivity = function() {
if (!this._connected) {
return;
}
if (isNaN(this._lastLedgerClose)) {
return;
}
var delta = (Date.now() - this._lastLedgerClose);
if (delta > (1000 * 25)) {
this.reconnect();
}
};
/**
* Server maintains a score for request prioritization.
*
* The score is determined by various data including
* this server's lag to receive ledger_closed events,
* ping response time, and load(fee) change
*
* @param {String} type
* @param {Object} data
* @api private
*/
Server.prototype._updateScore = function(type, data) {
if (!this._connected) {
return;
}
var weight = this._scoreWeights[type] || 1;
switch (type) {
case 'ledgerclose':
// Ledger lag
var delta = data.ledger_index - this._lastLedgerIndex;
if (delta > 0) {
this._score += weight * delta;
}
break;
case 'response':
// Ping lag
var delta = Math.floor((Date.now() - data.time) / 200);
this._score += weight * delta;
break;
case 'loadchange':
// Load/fee change
this._fee = Number(this._computeFee(10));
break;
}
if (this._score > 1e3) {
this.reconnect();
}
};
/**
* Get the remote address for a server.
* Incompatible with ripple-lib client build
*/
Server.prototype._remoteAddress = function() {
var address;
try {
address = this._ws._socket.remoteAddress;
} catch (e) {
}
return address;
};
/**
* Disconnect from rippled WebSocket server
*
* @api public
*/
Server.prototype.disconnect = function() {
this._shouldConnect = false;
this._setState('offline');
if (this._ws) {
this._ws.close();
}
};
/**
* Reconnect to rippled WebSocket server
*
* @api public
*/
Server.prototype.reconnect = function() {
var self = this;
function disconnected() {
self.connect();
};
if (this._ws) {
this.once('disconnect', disconnected);
this.disconnect();
}
};
/**
* Connect to rippled WebSocket server and subscribe to events that are
* internally requisite. Automatically retry connections with a gradual
* back-off
*
* @api public
*/
Server.prototype.connect = function() {
var self = this;
// We don't connect if we believe we're already connected. This means we have
// recently received a message from the server and the WebSocket has not
// reported any issues either. If we do fail to ping or the connection drops,
// we will automatically reconnect.
if (this._connected === true) return;
if (this._remote.trace) console.log('server: connect: %s', this._opts.url);
// Ensure any existing socket is given the command to close first.
if (this._ws) this._ws.close();
// We require this late, because websocket shims may be loaded after
// ripple-lib.
var WebSocket = require('ws');
var ws = this._ws = new WebSocket(this._opts.url);
this._should_connect = true;
self.emit('connecting');
ws.onopen = function () {
// If we are no longer the active socket, simply ignore any event
if (ws !== self._ws) return;
self.emit('socket_open');
// Subscribe to events
var request = self._remote._server_prepare_subscribe();
self.request(request);
};
ws.onerror = function (e) {
// If we are no longer the active socket, simply ignore any event
if (ws !== self._ws) return;
if (self._remote.trace) console.log('server: onerror: %s', e.data || e);
// Most connection errors for WebSockets are conveyed as 'close' events with
// code 1006. This is done for security purposes and therefore unlikely to
// ever change.
// This means that this handler is hardly ever called in practice. If it is,
// it probably means the server's WebSocket implementation is corrupt, or
// the connection is somehow producing corrupt data.
// Most WebSocket applications simply log and ignore this error. Once we
// support for multiple servers, we may consider doing something like
// lowering this server's quality score.
// However, in Node.js this event may be triggered instead of the close
// event, so we need to handle it.
handleConnectionClose();
};
// Failure to open.
ws.onclose = function () {
// If we are no longer the active socket, simply ignore any event
if (ws !== self._ws) return;
if (self._remote.trace) console.log('server: onclose: %s', ws.readyState);
handleConnectionClose();
};
function handleConnectionClose() {
self.emit('socket_close');
self._set_state('offline');
// Prevent additional events from this socket
ws.onopen = ws.onerror = ws.onclose = ws.onmessage = function () {};
// Should we be connected?
if (!self._should_connect) return;
// Delay and retry.
self._retry += 1;
self._retry_timer = setTimeout(function () {
if (self._remote.trace) console.log('server: retry');
if (!self._should_connect) return;
self.connect();
}, self._retry < 40
? 1000/20 // First, for 2 seconds: 20 times per second
: self._retry < 40+60
? 1000 // Then, for 1 minute: once per second
: self._retry < 40+60+60
? 10*1000 // Then, for 10 minutes: once every 10 seconds
: 30*1000); // Then: once every 30 seconds
if (this._connected) {
return;
}
ws.onmessage = function (msg) {
self.emit('message', msg.data);
};
};
if (this._remote.trace) {
log.info('connect:', this._opts.url);
}
Server.prototype.disconnect = function () {
this._should_connect = false;
this._set_state('offline');
// Ensure any existing socket is given the command to close first.
if (this._ws) {
this._ws.close();
}
};
Server.prototype.send_message = function (message) {
this._ws.send(JSON.stringify(message));
var WebSocket = Server.websocketConstructor();
if (!WebSocket) {
throw new Error('No websocket support detected!');
}
var ws = this._ws = new WebSocket(this._opts.url);
this._shouldConnect = true;
self.emit('connecting');
ws.onmessage = function onMessage(msg) {
self.emit('message', msg.data);
};
ws.onopen = function onOpen() {
if (ws === self._ws) {
self.emit('socket_open');
// Subscribe to events
self._request(self._remote._serverPrepareSubscribe());
}
};
ws.onerror = function onError(e) {
if (ws === self._ws) {
self.emit('socket_error');
if (self._remote.trace) {
log.info('onerror:', self._opts.url, e.data || e);
}
// Most connection errors for WebSockets are conveyed as 'close' events with
// code 1006. This is done for security purposes and therefore unlikely to
// ever change.
// This means that this handler is hardly ever called in practice. If it is,
// it probably means the server's WebSocket implementation is corrupt, or
// the connection is somehow producing corrupt data.
// Most WebSocket applications simply log and ignore this error. Once we
// support for multiple servers, we may consider doing something like
// lowering this server's quality score.
// However, in Node.js this event may be triggered instead of the close
// event, so we need to handle it.
self._handleClose();
}
};
ws.onclose = function onClose() {
if (ws === self._ws) {
if (self._remote.trace) {
log.info('onclose:', self._opts.url, ws.readyState);
}
self._handleClose();
}
};
};
/**
* Submit a Request object to this server.
* Retry connection to rippled server
*
* @api private
*/
Server.prototype.request = function (request) {
Server.prototype._retryConnect = function() {
var self = this;
this._retry += 1;
var retryTimeout = (this._retry < 40)
// First, for 2 seconds: 20 times per second
? (1000 / 20)
: (this._retry < 40 + 60)
// Then, for 1 minute: once per second
? (1000)
: (this._retry < 40 + 60 + 60)
// Then, for 10 minutes: once every 10 seconds
? (10 * 1000)
// Then: once every 30 seconds
: (30 * 1000);
function connectionRetry() {
if (self._shouldConnect) {
if (self._remote.trace) {
log.info('retry', self._opts.url);
}
self.connect();
}
};
this._retryTimer = setTimeout(connectionRetry, retryTimeout);
};
/**
* Handle connection closes
*
* @api private
*/
Server.prototype._handleClose = function() {
var self = this;
var ws = this._ws;
this.emit('socket_close');
this._setState('offline');
function noOp(){};
// Prevent additional events from this socket
ws.onopen = ws.onerror = ws.onclose = ws.onmessage = noOp;
if (self._shouldConnect) {
this._retryConnect();
}
};
/**
* Handle incoming messages from rippled WebSocket server
*
* @param {JSON-parseable} message
* @api private
*/
Server.prototype._handleMessage = function(message) {
var self = this;
try {
message = JSON.parse(message);
} catch(e) {
}
if (!Server.isValidMessage(message)) {
this.emit('unexpected', message);
return;
}
switch (message.type) {
case 'ledgerClosed':
this._handleLedgerClosed(message);
break;
case 'serverStatus':
this._handleServerStatus(message);
break;
case 'response':
this._handleResponse(message);
break;
case 'path_find':
this._handlePathFind(message);
break;
}
};
Server.prototype._handleLedgerClosed = function(message) {
this._lastLedgerIndex = message.ledger_index;
this._lastLedgerClose = Date.now();
this.emit('ledger_closed', message);
};
Server.prototype._handleServerStatus = function(message) {
// This message is only received when online.
// As we are connected, it is the definitive final state.
var isOnline = ~Server.onlineStates.indexOf(message.server_status);
this._setState(isOnline ? 'online' : 'offline');
if (!Server.isLoadStatus(message)) {
return;
}
this.emit('load', message, this);
this._remote.emit('load', message, this);
var loadChanged = message.load_base !== this._load_base
|| message.load_factor !== this._load_factor
if (loadChanged) {
this._load_base = message.load_base;
this._load_factor = message.load_factor;
this.emit('load_changed', message, this);
this._remote.emit('load_changed', message, this);
}
};
Server.prototype._handleResponse = function(message) {
// A response to a request.
var request = this._requests[message.id];
delete this._requests[message.id];
if (!request) {
if (this._remote.trace) {
log.info('UNEXPECTED:', this._opts.url, message);
}
return;
}
if (message.status === 'success') {
if (this._remote.trace) {
log.info('response:', this._opts.url, message);
}
var command = request.message.command;
var result = message.result;
var responseEvent = 'response_' + command;
request.emit('success', result);
[ this, this._remote ].forEach(function(emitter) {
emitter.emit(responseEvent, result, request, message);
});
} else if (message.error) {
if (this._remote.trace) {
log.info('error:', this._opts.url, message);
}
var error = {
error: 'remoteError',
error_message: 'Remote reported an error.',
remote: message
};
request.emit('error', error);
}
};
Server.prototype._handlePathFind = function(message) {
if (this._remote.trace) {
log.info('path_find:', this._opts.url, message);
}
};
/**
* Handle subscription response messages. Subscription response
* messages indicate that a connection to the server is ready
*
* @api private
*/
Server.prototype._handleResponseSubscribe = function(message) {
if (~(Server.onlineStates.indexOf(message.server_status))) {
this._setState('online');
}
if (Server.isLoadStatus(message)) {
this._load_base = message.load_base || 256;
this._load_factor = message.load_factor || 256;
this._fee_ref = message.fee_ref;
this._fee_base = message.fee_base;
this._reserve_base = message.reserve_base;
this._reserve_inc = message.reserve_inc;
}
};
/**
* Check that received message from rippled is valid
*
* @api private
*/
Server.isValidMessage = function(message) {
return (typeof message === 'object')
&& (typeof message.type === 'string');
};
/**
* Check that received serverStatus message contains
* load status information
*
* @api private
*/
Server.isLoadStatus = function(message) {
return (typeof message.load_base === 'number')
&& (typeof message.load_factor === 'number');
};
/**
* Send JSON message to rippled WebSocket server
*
* @param {JSON-Stringifiable} message
* @api private
*/
Server.prototype._sendMessage = function(message) {
if (this._ws) {
if (this._remote.trace) {
log.info('request:', this._opts.url, message);
}
this._ws.send(JSON.stringify(message));
}
};
/**
* Submit a Request object.
*
* Requests are indexed by message ID, which is repeated
* in the response from rippled WebSocket server
*
* @param {Request} request
* @api private
*/
Server.prototype._request = function(request) {
var self = this;
// Only bother if we are still connected.
if (self._ws) {
request.message.id = self._id;
self._requests[request.message.id] = request;
// Advance message ID
self._id++;
if (self._connected || (request.message.command === 'subscribe' && self._ws.readyState === 1)) {
if (self._remote.trace) {
utils.logObject('server: request: %s', request.message);
}
self.send_message(request.message);
} else {
// XXX There are many ways to make self smarter.
self.once('connect', function () {
if (self._remote.trace) {
utils.logObject('server: request: %s', request.message);
}
self.send_message(request.message);
});
if (!this._ws) {
if (this._remote.trace) {
log.info('request: DROPPING:', self._opts.url, request.message);
}
return;
}
request.server = this;
request.message.id = this._id;
request.time = Date.now();
this._requests[request.message.id] = request;
// Advance message ID
this._id++;
function sendRequest() {
self._sendMessage(request.message);
};
if (this._isConnected(request)) {
sendRequest();
} else {
if (self._remote.trace) {
utils.logObject('server: request: DROPPING: %s', request.message);
}
// XXX There are many ways to make this smarter.
this.once('connect', sendRequest);
}
};
Server.prototype._handle_message = function (json) {
var self = this;
Server.prototype._isConnected = function(request) {
var isSubscribeRequest = request
&& request.message.command === 'subscribe'
&& this._ws.readyState === 1;
var message;
try {
message = JSON.parse(json);
} catch(exception) { return; }
switch(message.type) {
case 'response':
// A response to a request.
var request = self._requests[message.id];
delete self._requests[message.id];
if (!request) {
if (self._remote.trace) utils.logObject('server: UNEXPECTED: %s', message);
} else if ('success' === message.status) {
if (self._remote.trace) utils.logObject('server: response: %s', message);
request.emit('success', message.result);
[ self, self._remote ].forEach(function(emitter) {
emitter.emit('response_' + request.message.command, message.result, request, message);
});
} else if (message.error) {
if (self._remote.trace) utils.logObject('server: error: %s', message);
request.emit('error', {
'error' : 'remoteError',
'error_message' : 'Remote reported an error.',
'remote' : message
});
}
break;
case 'serverStatus':
// This message is only received when online. As we are connected, it is the definative final state.
self._set_state(self._is_online(message.server_status) ? 'online' : 'offline');
break;
}
return this._connected || (this._ws && isSubscribeRequest);
};
Server.prototype._handle_response_subscribe = function (message) {
var self = this;
/**
* Calculate transaction fee
*
* @param {Transaction|Number} Fee units for a provided transaction
* @return {Number} Final fee in XRP for specified number of fee units
* @api private
*/
self._server_status = message.server_status;
Server.prototype._computeFee = function(transaction) {
var units;
if (self._is_online(message.server_status)) {
self._set_state('online');
if (transaction instanceof Transaction) {
units = transaction._getFeeUnits();
} else if (typeof transaction === 'number') {
units = transaction;
} else {
throw new Error('Invalid argument');
}
return this._feeTx(units).to_json();
};
/**
* Calculate a transaction fee for a number of tx fee units.
*
* This takes into account the last known network and local load fees.
*
* @param {Number} Fee units for a provided transaction
* @return {Amount} Final fee in XRP for specified number of fee units.
*/
Server.prototype._feeTx = function(units) {
var fee_unit = this._feeTxUnit();
return Amount.from_json(String(Math.ceil(units * fee_unit)));
};
/**
* Get the current recommended transaction fee unit.
*
* Multiply this value with the number of fee units in order to calculate the
* recommended fee for the transaction you are trying to submit.
*
* @return {Number} Recommended amount for one fee unit as float.
*/
Server.prototype._feeTxUnit = function() {
var fee_unit = this._fee_base / this._fee_ref;
// Apply load fees
fee_unit *= this._load_factor / this._load_base;
// Apply fee cushion (a safety margin in case fees rise since we were last updated)
fee_unit *= this._fee_cushion;
return fee_unit;
};
/**
* Get the current recommended reserve base.
*
* Returns the base reserve with load fees and safety margin applied.
*/
Server.prototype._reserve = function(ownerCount) {
var reserve_base = Amount.from_json(String(this._reserve_base));
var reserve_inc = Amount.from_json(String(this._reserve_inc));
var owner_count = ownerCount || 0;
if (owner_count < 0) {
throw new Error('Owner count must not be negative.');
}
return reserve_base.add(reserve_inc.product_human(owner_count));
};
exports.Server = Server;

168
src/js/ripple/shamap.js Normal file
View File

@@ -0,0 +1,168 @@
var util = require('util');
var sjcl = require('./utils').sjcl;
var stypes = require('./serializedtypes');
var hashprefixes = require('./hashprefixes');
var UInt256 = require('./uint256').UInt256;
var SerializedObject = require('./serializedobject').SerializedObject;
function SHAMap() {
this.root = new SHAMapTreeNodeInner(0);
};
SHAMap.prototype.add_item = function(tag, node, type) {
var node = new SHAMapTreeNodeLeaf(tag, node, type);
this.root.add_item(tag, node);
};
SHAMap.prototype.hash = function() {
return this.root.hash();
};
/**
* Abstract class representing a node in a SHAMap tree.
*
* Can be either SHAMapTreeNodeInner or SHAMapTreeNodeLeaf.
*/
function SHAMapTreeNode() { };
SHAMapTreeNode.TYPE_INNER = 1;
SHAMapTreeNode.TYPE_TRANSACTION_NM = 2;
SHAMapTreeNode.TYPE_TRANSACTION_MD = 3;
SHAMapTreeNode.TYPE_ACCOUNT_STATE = 4;
/**
* @param tag {String} 64 hexadecimal characters
*/
SHAMapTreeNode.prototype.add_item = function(tag, node) {
throw new Error('Called unimplemented virtual method SHAMapTreeNode#add_item.');
};
SHAMapTreeNode.prototype.hash = function() {
throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.');
};
/**
* Inner (non-leaf) node in a SHAMap tree.
*/
function SHAMapTreeNodeInner(depth) {
SHAMapTreeNode.call(this);
this.leaves = {};
this.type = SHAMapTreeNode.INNER;
this.depth = depth == null ? 0 : depth;
this.empty = true;
}
util.inherits(SHAMapTreeNodeInner, SHAMapTreeNode);
/**
* @param tag {String} (equates to a ledger entries `index`)
*/
SHAMapTreeNodeInner.prototype.add_item = function (tag, node) {
var depth = this.depth;
var existing_node = this.get_node(tag[depth]);
if (existing_node) {
// A node already exists in this slot
if (existing_node instanceof SHAMapTreeNodeInner) {
// There is an inner node, so we need to go deeper
existing_node.add_item(tag, node);
} else if (existing_node.tag === tag) {
// Collision
throw new Error('Tried to add a node to a SHAMap that was already in there.');
} else {
// Turn it into an inner node
var new_inner_node = new SHAMapTreeNodeInner(depth + 1);
// Parent new and existing node
new_inner_node.add_item(existing_node.tag, existing_node);
new_inner_node.add_item(tag, node);
// And place the newly created inner node in the slot
this.set_node(tag[depth], new_inner_node);
}
} else {
// Neat, we have a nice open spot for the new node
this.set_node(tag[depth], node);
}
};
/**
* Overwrite the node that is currently in a given slot.
*/
SHAMapTreeNodeInner.prototype.set_node = function(slot, node) {
this.leaves[slot] = node;
this.empty = false;
};
SHAMapTreeNodeInner.prototype.get_node = function(slot) {
return this.leaves[slot];
};
SHAMapTreeNodeInner.prototype.hash = function() {
if (this.empty) {
return UInt256.from_hex(UInt256.HEX_ZERO);
}
var hash_buffer = new SerializedObject();
var buffer = [ ];
for (var i=0; i<16; i++) {
var leafHash = UInt256.from_hex(UInt256.HEX_ZERO);
var slot = i.toString(16).toUpperCase();
if (typeof this.leaves[slot] === 'object') {
leafHash = this.leaves[slot].hash();
}
hash_buffer.append(leafHash.to_bytes());
}
var hash = hash_buffer.hash(hashprefixes.HASH_INNER_NODE);
return UInt256.from_bits(hash);
};
/**
* Leaf node in a SHAMap tree.
*/
function SHAMapTreeNodeLeaf(tag, node, type) {
SHAMapTreeNode.call(this);
if (typeof tag !== 'string') {
throw new Error('Tag is unexpected type.');
}
this.tag = tag;
this.tag_bytes = UInt256.from_hex(this.tag).to_bytes();
this.type = type;
this.node = node;
};
util.inherits(SHAMapTreeNodeLeaf, SHAMapTreeNode);
SHAMapTreeNodeLeaf.prototype.hash = function () {
var buffer = new SerializedObject();
switch (this.type) {
case SHAMapTreeNode.TYPE_ACCOUNT_STATE:
buffer.append(this.node);
buffer.append(this.tag_bytes);
return buffer.hash(hashprefixes.HASH_LEAF_NODE);
case SHAMapTreeNode.TYPE_TRANSACTION_NM:
return this.tag_bytes;
case SHAMapTreeNode.TYPE_TRANSACTION_MD:
buffer.append(this.node);
buffer.append(this.tag_bytes);
return buffer.hash(hashprefixes.HASH_TX_NODE);
default:
throw new Error('Tried to hash a SHAMap node of unknown type.');
}
};
exports.SHAMap = SHAMap;
exports.SHAMapTreeNode = SHAMapTreeNode;
exports.SHAMapTreeNodeInner = SHAMapTreeNodeInner;
exports.SHAMapTreeNodeLeaf = SHAMapTreeNodeLeaf;

View File

@@ -0,0 +1,203 @@
var Crypt = require('./crypt').Crypt;
var Message = require('./message').Message;
var parser = require("url");
var querystring = require('querystring');
var extend = require("extend");
var SignedRequest = function (config) {
// XXX Constructor should be generalized and constructing from an Angular.js
// $http config should be a SignedRequest.from... utility method.
this.config = extend(true, {}, config);
if (!this.config.data) this.config.data = {};
};
/**
* Create a string from request parameters that
* will be used to sign a request
* @param {Object} parsed - parsed url
* @param {Object} date
* @param {Object} mechanism - type of signing
*/
SignedRequest.prototype.getStringToSign = function (parsed, date, mechanism) {
// XXX This method doesn't handle signing GET requests correctly. The data
// field will be merged into the search string, not the request body.
// Sort the properties of the JSON object into canonical form
var canonicalData = JSON.stringify(copyObjectWithSortedKeys(this.config.data));
// Canonical request using Amazon's v4 signature format
// See: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
var canonicalRequest = [
this.config.method || 'GET',
parsed.pathname || '',
parsed.search || '',
// XXX Headers signing not supported
'',
'',
Crypt.hashSha512(canonicalData).toLowerCase()
].join('\n');
// String to sign inspired by Amazon's v4 signature format
// See: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
//
// We don't have a credential scope, so we skip it.
//
// But that modifies the format, so the format ID is RIPPLE1, instead of AWS4.
return [
mechanism,
date,
Crypt.hashSha512(canonicalRequest).toLowerCase()
].join('\n');
};
//prepare for signing
function copyObjectWithSortedKeys(object) {
if (isPlainObject(object)) {
var newObj = {};
var keysSorted = Object.keys(object).sort();
var key;
for (var i in keysSorted) {
key = keysSorted[i];
if (Object.prototype.hasOwnProperty.call(object, key)) {
newObj[key] = copyObjectWithSortedKeys(object[key]);
}
}
return newObj;
} else if (Array.isArray(object)) {
return object.map(copyObjectWithSortedKeys);
} else {
return object;
}
}
//from npm extend
function isPlainObject(obj) {
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
};
/**
* HMAC signed request
* @param {Object} config
* @param {Object} auth_secret
* @param {Object} blob_id
*/
SignedRequest.prototype.signHmac = function (auth_secret, blob_id) {
var config = extend(true, {}, this.config);
// Parse URL
var parsed = parser.parse(config.url);
var date = dateAsIso8601();
var signatureType = 'RIPPLE1-HMAC-SHA512';
var stringToSign = this.getStringToSign(parsed, date, signatureType);
var signature = Crypt.signString(auth_secret, stringToSign);
var query = querystring.stringify({
signature: Crypt.base64ToBase64Url(signature),
signature_date: date,
signature_blob_id: blob_id,
signature_type: signatureType
});
config.url += (parsed.search ? '&' : '?') + query;
return config;
};
/**
* Asymmetric signed request
* @param {Object} config
* @param {Object} secretKey
* @param {Object} account
* @param {Object} blob_id
*/
SignedRequest.prototype.signAsymmetric = function (secretKey, account, blob_id) {
var config = extend(true, {}, this.config);
// Parse URL
var parsed = parser.parse(config.url);
var date = dateAsIso8601();
var signatureType = 'RIPPLE1-ECDSA-SHA512';
var stringToSign = this.getStringToSign(parsed, date, signatureType);
var signature = Message.signMessage(stringToSign, secretKey);
var query = querystring.stringify({
signature: Crypt.base64ToBase64Url(signature),
signature_date: date,
signature_blob_id: blob_id,
signature_account: account,
signature_type: signatureType
});
config.url += (parsed.search ? '&' : '?') + query;
return config;
};
/**
* Asymmetric signed request for vault recovery
* @param {Object} config
* @param {Object} secretKey
* @param {Object} username
*/
SignedRequest.prototype.signAsymmetricRecovery = function (secretKey, username) {
var config = extend(true, {}, this.config);
// Parse URL
var parsed = parser.parse(config.url);
var date = dateAsIso8601();
var signatureType = 'RIPPLE1-ECDSA-SHA512';
var stringToSign = this.getStringToSign(parsed, date, signatureType);
var signature = Message.signMessage(stringToSign, secretKey);
var query = querystring.stringify({
signature: Crypt.base64ToBase64Url(signature),
signature_date: date,
signature_username: username,
signature_type: signatureType
});
config.url += (parsed.search ? '&' : '?') + query;
return config;
};
var dateAsIso8601 = (function () {
function pad(n) {
return (n < 0 || n > 9 ? "" : "0") + n;
}
return function dateAsIso8601() {
var date = new Date();
return date.getUTCFullYear() + "-" +
pad(date.getUTCMonth() + 1) + "-" +
pad(date.getUTCDate()) + "T" +
pad(date.getUTCHours()) + ":" +
pad(date.getUTCMinutes()) + ":" +
pad(date.getUTCSeconds()) + ".000Z";
};
})();
// XXX Add methods for verifying requests
// SignedRequest.prototype.verifySignatureHmac
// SignedRequest.prototype.verifySignatureAsymetric
exports.SignedRequest = SignedRequest;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,668 @@
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Transaction = require('./transaction').Transaction;
var RippleError = require('./rippleerror').RippleError;
var PendingQueue = require('./transactionqueue').TransactionQueue;
var log = require('./log').internal.sub('transactionmanager');
/**
* @constructor TransactionManager
* @param {Account} account
*/
function TransactionManager(account) {
EventEmitter.call(this);
var self = this;
this._account = account;
this._accountID = account._account_id;
this._remote = account._remote;
this._nextSequence = void(0);
this._maxFee = this._remote.max_fee;
this._submissionTimeout = this._remote._submission_timeout;
this._pending = new PendingQueue();
// Query remote server for next account sequence number
this._loadSequence();
function transactionReceived(res) {
var transaction = TransactionManager.normalizeTransaction(res);
var sequence = transaction.tx_json.Sequence;
var hash = transaction.tx_json.hash;
if (!transaction.validated) {
return;
}
self._pending.addReceivedSequence(sequence);
// ND: we need to check against all submissions IDs
var submission = self._pending.getSubmission(hash);
if (self._remote.trace) {
log.info('transaction received:', transaction.tx_json);
}
if (submission instanceof Transaction) {
// ND: A `success` handler will `finalize` this later
submission.emit('success', transaction);
} else {
self._pending.addReceivedId(hash, transaction);
}
};
this._account.on('transaction-outbound', transactionReceived);
this._remote.on('load_changed', this._adjustFees.bind(this));
function updatePendingStatus(ledger) {
self._pending.forEach(function(pending) {
switch (ledger.ledger_index - pending.submitIndex) {
case 8:
pending.emit('lost', ledger);
break;
case 4:
pending.emit('missing', ledger);
break;
}
});
};
this._remote.on('ledger_closed', updatePendingStatus);
function remoteReconnected(callback) {
var callback = (typeof callback === 'function') ? callback : function(){};
if (!self._pending.length) {
return callback();
}
//Load account transaction history
var options = {
account: self._accountID,
ledger_index_min: -1,
ledger_index_max: -1,
binary: true,
parseBinary: true,
limit: 100,
filter: 'outbound'
};
function accountTx(err, transactions) {
if (!err && Array.isArray(transactions.transactions)) {
transactions.transactions.forEach(transactionReceived);
}
self._remote.on('ledger_closed', updatePendingStatus);
//Load next transaction sequence
self._loadSequence(self._resubmit.bind(self));
callback();
};
self._remote.requestAccountTx(options, accountTx);
self.emit('reconnect');
};
function remoteDisconnected() {
self._remote.once('connect', remoteReconnected);
self._remote.removeListener('ledger_closed', updatePendingStatus);
};
this._remote.on('disconnect', remoteDisconnected);
function saveTransaction(transaction) {
self._remote.storage.saveTransaction(transaction.summary());
};
if (this._remote.storage) {
this.on('save', saveTransaction);
}
};
util.inherits(TransactionManager, EventEmitter);
//Normalize transactions received from account
//transaction stream and account_tx
TransactionManager.normalizeTransaction = function(tx) {
var transaction = { };
Object.keys(tx).forEach(function(key) {
transaction[key] = tx[key];
});
if (!tx.engine_result) {
// account_tx
transaction = {
engine_result: tx.meta.TransactionResult,
tx_json: tx.tx,
hash: tx.tx.hash,
ledger_index: tx.tx.ledger_index,
meta: tx.meta,
type: 'transaction',
validated: true
};
transaction.result = transaction.engine_result;
transaction.result_message = transaction.engine_result_message;
}
if (!transaction.metadata) {
transaction.metadata = transaction.meta;
}
if (!transaction.tx_json) {
transaction.tx_json = transaction.transaction;
}
delete transaction.transaction;
delete transaction.mmeta;
delete transaction.meta;
return transaction;
};
// Transaction fees are adjusted in real-time
TransactionManager.prototype._adjustFees = function(loadData) {
// ND: note, that `Fee` is a component of a transactionID
var self = this;
if (!this._remote.local_fee) {
return;
}
this._pending.forEach(function(pending) {
var oldFee = pending.tx_json.Fee;
var newFee = pending._computeFee();
function maxFeeExceeded() {
pending.once('presubmit', function() {
pending.emit('error', 'tejMaxFeeExceeded');
});
};
if (Number(newFee) > self._maxFee) {
return maxFeeExceeded();
}
pending.tx_json.Fee = newFee;
pending.emit('fee_adjusted', oldFee, newFee);
if (self._remote.trace) {
log.info('fee adjusted:', pending.tx_json, oldFee, newFee);
}
});
};
//Fill an account transaction sequence
TransactionManager.prototype._fillSequence = function(tx, callback) {
var self = this;
function submitFill(sequence, callback) {
var fill = self._remote.transaction();
fill.account_set(self._accountID);
fill.tx_json.Sequence = sequence;
fill.once('submitted', callback);
// Secrets may be set on a per-transaction basis
if (tx._secret) {
fill.secret(tx._secret);
}
fill.submit();
};
function sequenceLoaded(err, sequence) {
if (typeof sequence !== 'number') {
return callback(new Error('Failed to fetch account transaction sequence'));
}
var sequenceDif = tx.tx_json.Sequence - sequence;
var submitted = 0;
;(function nextFill(sequence) {
if (sequence >= tx.tx_json.Sequence) {
return;
}
submitFill(sequence, function() {
if (++submitted === sequenceDif) {
callback();
} else {
nextFill(sequence + 1);
}
});
})(sequence);
};
this._loadSequence(sequenceLoaded);
};
TransactionManager.prototype._loadSequence = function(callback) {
var self = this;
function sequenceLoaded(err, sequence) {
if (typeof sequence === 'number') {
self._nextSequence = sequence;
self.emit('sequence_loaded', sequence);
if (typeof callback === 'function') {
callback(err, sequence);
}
} else {
setTimeout(function() {
self._loadSequence(callback);
}, 1000 * 3);
}
};
this._account.getNextSequence(sequenceLoaded);
};
TransactionManager.prototype._resubmit = function(ledgers, pending) {
var self = this;
var pending = pending ? [ pending ] : this._pending;
var ledgers = Number(ledgers) || 0;
function resubmitTransaction(pending) {
if (!pending || pending.finalized) {
// Transaction has been finalized, nothing to do
return;
}
var hashCached = pending.findId(self._pending._idCache);
if (self._remote.trace) {
log.info('resubmit:', pending.tx_json);
}
if (hashCached) {
return pending.emit('success', hashCached);
}
while (self._pending.hasSequence(pending.tx_json.Sequence)) {
//Sequence number has been consumed by another transaction
pending.tx_json.Sequence += 1;
if (self._remote.trace) {
log.info('incrementing sequence:', pending.tx_json);
}
}
self._request(pending);
};
function resubmitTransactions() {
;(function nextTransaction(i) {
var transaction = pending[i];
if (!(transaction instanceof Transaction)) {
return;
}
transaction.once('submitted', function(m) {
transaction.emit('resubmitted', m);
self._loadSequence();
if (++i < pending.length) {
nextTransaction(i);
}
});
resubmitTransaction(transaction);
})(0);
};
this._waitLedgers(ledgers, resubmitTransactions);
};
TransactionManager.prototype._waitLedgers = function(ledgers, callback) {
if (ledgers < 1) {
return callback();
}
var self = this;
var closes = 0;
function ledgerClosed() {
if (++closes < ledgers) {
return;
}
self._remote.removeListener('ledger_closed', ledgerClosed);
callback();
};
this._remote.on('ledger_closed', ledgerClosed);
};
TransactionManager.prototype._request = function(tx) {
var self = this;
var remote = this._remote;
if (tx.attempts > 10) {
return tx.emit('error', new RippleError('tejAttemptsExceeded'));
}
if (tx.attempts > 0 && !remote.local_signing) {
var message = ''
+ 'It is not possible to resubmit transactions automatically safely without '
+ 'synthesizing the transactionID locally. See `local_signing` config option';
return tx.emit('error', new RippleError('tejLocalSigningRequired', message));
}
tx.emit('presubmit');
if (tx.finalized) {
return;
}
if (remote.trace) {
log.info('submit transaction:', tx.tx_json);
}
function transactionProposed(message) {
if (tx.finalized) {
return;
}
// If server is honest, don't expect a final if rejected.
message.rejected = tx.isRejected(message.engine_result_code);
tx.emit('proposed', message);
};
function transactionFailed(message) {
if (tx.finalized) {
return;
}
switch (message.engine_result) {
case 'tefPAST_SEQ':
self._resubmit(1, tx);
break;
default:
tx.emit('error', message);
}
};
function transactionRetry(message) {
if (tx.finalized) {
return;
}
self._fillSequence(tx, function() {
self._resubmit(1, tx);
});
};
function transactionFeeClaimed(message) {
if (tx.finalized) {
return;
}
tx.emit('error', message);
};
function transactionFailedLocal(message) {
if (tx.finalized) {
return;
}
if (self._remote.local_fee && (message.engine_result === 'telINSUF_FEE_P')) {
self._resubmit(2, tx);
} else {
submissionError(message);
}
};
function submissionError(error) {
// Finalized (e.g. aborted) transactions must stop all activity
if (tx.finalized) {
return;
}
if (TransactionManager._isTooBusy(error)) {
self._resubmit(1, tx);
} else {
self._nextSequence--;
tx.emit('error', error);
}
};
function submitted(message) {
// Finalized (e.g. aborted) transactions must stop all activity
if (tx.finalized) {
return;
}
// ND: If for some unknown reason our hash wasn't computed correctly this is
// an extra measure.
if (message.tx_json && message.tx_json.hash) {
tx.addId(message.tx_json.hash);
}
message.result = message.engine_result || '';
tx.result = message;
if (remote.trace) {
log.info('submit response:', message);
}
tx.emit('submitted', message);
switch (message.result.slice(0, 3)) {
case 'tes':
transactionProposed(message);
break;
case 'tec':
transactionFeeClaimed(message);
break;
case 'ter':
transactionRetry(message);
break;
case 'tef':
transactionFailed(message);
break;
case 'tel':
transactionFailedLocal(message);
break;
default:
// tem
submissionError(message);
}
};
var submitRequest = remote.requestSubmit();
submitRequest.once('error', submitted);
submitRequest.once('success', submitted);
function prepareSubmit() {
if (remote.local_signing) {
// TODO: We are serializing twice, when we could/should be feeding the
// tx_blob to `tx.hash()` which rebuilds it to sign it.
submitRequest.tx_blob(tx.serialize().to_hex());
// ND: ecdsa produces a random `TxnSignature` field value, a component of
// the hash. Attempting to identify a transaction via a hash synthesized
// locally while using remote signing is inherently flawed.
tx.addId(tx.hash());
} else {
// ND: `build_path` is completely ignored when doing local signing as
// `Paths` is a component of the signed blob, the `tx_blob` is signed,
// sealed and delivered, and the txn unmodified.
// TODO: perhaps an exception should be raised if build_path is attempted
// while local signing
submitRequest.build_path(tx._build_path);
submitRequest.secret(tx._secret);
submitRequest.tx_json(tx.tx_json);
}
if (tx._server) {
submitRequest.server = tx._server;
}
submitTransaction();
};
function requestTimeout() {
// ND: What if the response is just slow and we get a response that
// `submitted` above will cause to have concurrent resubmit logic streams?
// It's simpler to just mute handlers and look out for finalized
// `transaction` messages.
// ND: We should audit the code for other potential multiple resubmit
// streams. Connection/reconnection could be one? That's why it's imperative
// that ALL transactionIDs sent over network are tracked.
// Finalized (e.g. aborted) transactions must stop all activity
if (tx.finalized) {
return;
}
tx.emit('timeout');
if (remote._connected) {
if (remote.trace) {
log.info('timeout:', tx.tx_json);
}
self._resubmit(3, tx);
}
};
function submitTransaction() {
if (tx.finalized) {
return;
}
submitRequest.timeout(self._submissionTimeout, requestTimeout);
submitRequest.broadcast();
tx.attempts++;
tx.emit('postsubmit');
};
tx.submitIndex = this._remote._ledger_current_index;
if (tx.attempts === 0) {
tx.initialSubmitIndex = tx.submitIndex;
}
if (!tx._setLastLedger) {
// Honor LastLedgerSequence set by user of API. If
// left unset by API, bump LastLedgerSequence
tx.tx_json.LastLedgerSequence = tx.submitIndex + 8;
}
tx.lastLedgerSequence = tx.tx_json.LastLedgerSequence;
if (remote.local_signing) {
tx.sign(prepareSubmit);
} else {
prepareSubmit();
}
return submitRequest;
};
TransactionManager._isNoOp = function(transaction) {
return (typeof transaction === 'object')
&& (typeof transaction.tx_json === 'object')
&& (transaction.tx_json.TransactionType === 'AccountSet')
&& (transaction.tx_json.Flags === 0);
};
TransactionManager._isRemoteError = function(error) {
return (typeof error === 'object')
&& (error.error === 'remoteError')
&& (typeof error.remote === 'object');
};
TransactionManager._isNotFound = function(error) {
return TransactionManager._isRemoteError(error)
&& /^(txnNotFound|transactionNotFound)$/.test(error.remote.error);
};
TransactionManager._isTooBusy = function(error) {
return TransactionManager._isRemoteError(error)
&& (error.remote.error === 'tooBusy');
};
/**
* Entry point for TransactionManager submission
*
* @param {Transaction} tx
*/
TransactionManager.prototype.submit = function(tx) {
var self = this;
var remote = this._remote;
// If sequence number is not yet known, defer until it is.
if (typeof this._nextSequence !== 'number') {
this.once('sequence_loaded', this.submit.bind(this, tx));
return;
}
// Finalized (e.g. aborted) transactions must stop all activity
if (tx.finalized) {
return;
}
function cleanup(message) {
// ND: We can just remove this `tx` by identity
self._pending.remove(tx);
tx.emit('final', message);
if (remote.trace) {
log.info('transaction finalized:', tx.tx_json, self._pending.getLength());
}
};
tx.once('cleanup', cleanup);
tx.on('save', function() {
self.emit('save', tx);
});
tx.once('error', function(message) {
tx._errorHandler(message);
});
tx.once('success', function(message) {
tx._successHandler(message);
});
tx.once('abort', function() {
tx.emit('error', new RippleError('tejAbort', 'Transaction aborted'));
});
if (typeof tx.tx_json.Sequence !== 'number') {
tx.tx_json.Sequence = this._nextSequence++;
}
// Attach secret, associate transaction with a server, attach fee.
// If the transaction can't complete, decrement sequence so that
// subsequent transactions
if (!tx.complete()) {
this._nextSequence--;
return;
}
tx.attempts = 0;
// ND: this is the ONLY place we put the tx into the queue. The
// TransactionQueue queue is merely a list, so any mutations to tx._hash
// will cause subsequent look ups (eg. inside 'transaction-outbound'
// validated transaction clearing) to fail.
this._pending.push(tx);
this._request(tx);
};
exports.TransactionManager = TransactionManager;

View File

@@ -0,0 +1,103 @@
/**
* Manager for pending transactions
*/
var LRU = require('lru-cache');
var Transaction = require('./transaction').Transaction;
function TransactionQueue() {
this._queue = [ ];
this._idCache = LRU();
this._sequenceCache = LRU();
};
/**
* Store received (validated) sequence
*/
TransactionQueue.prototype.addReceivedSequence = function(sequence) {
this._sequenceCache.set(String(sequence), true);
};
/**
* Check that sequence number has been consumed by a validated
* transaction
*/
TransactionQueue.prototype.hasSequence = function(sequence) {
return this._sequenceCache.has(String(sequence));
};
/**
* Store received (validated) ID transaction
*/
TransactionQueue.prototype.addReceivedId = function(id, transaction) {
this._idCache.set(id, transaction);
};
/**
* Get received (validated) transaction by ID
*/
TransactionQueue.prototype.getReceived = function(id) {
return this._idCache.get(id);
};
/**
* Get a submitted transaction by ID. Transactions
* may have multiple associated IDs.
*/
TransactionQueue.prototype.getSubmission = function(id) {
var result = void(0);
for (var i=0, tx; (tx=this._queue[i]); i++) {
if (~tx.submittedIDs.indexOf(id)) {
result = tx;
break;
}
}
return result;
};
/**
* Remove a transaction from the queue
*/
TransactionQueue.prototype.remove = function(tx) {
// ND: We are just removing the Transaction by identity
var i = this._queue.length;
if (typeof tx === 'string') {
tx = this.getSubmission(tx);
}
if (!(tx instanceof Transaction)) {
return;
}
while (i--) {
if (this._queue[i] === tx) {
this._queue.splice(i, 1);
break;
}
}
};
TransactionQueue.prototype.push = function(tx) {
this._queue.push(tx);
};
TransactionQueue.prototype.forEach = function(fn) {
this._queue.forEach(fn);
};
TransactionQueue.prototype.length =
TransactionQueue.prototype.getLength = function() {
return this._queue.length;
};
exports.TransactionQueue = TransactionQueue;

View File

@@ -1,31 +1,28 @@
var sjcl = require('../../../build/sjcl');
var utils = require('./utils');
var sjcl = utils.sjcl;
var config = require('./config');
var jsbn = require('./jsbn');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var Base = require('./base').Base;
var BigInteger = utils.jsbn.BigInteger;
//
// Abstract UInt class
//
// Base class for UInt??? classes
// Base class for UInt classes
//
var UInt = function () {
var UInt = function() {
// Internal form: NaN or BigInteger
this._value = NaN;
this._update();
};
UInt.json_rewrite = function (j, opts) {
UInt.json_rewrite = function(j, opts) {
return this.from_json(j).to_json(opts);
};
// Return a new UInt from j.
UInt.from_generic = function (j) {
UInt.from_generic = function(j) {
if (j instanceof this) {
return j.clone();
} else {
@@ -34,7 +31,7 @@ UInt.from_generic = function (j) {
};
// Return a new UInt from j.
UInt.from_hex = function (j) {
UInt.from_hex = function(j) {
if (j instanceof this) {
return j.clone();
} else {
@@ -43,7 +40,7 @@ UInt.from_hex = function (j) {
};
// Return a new UInt from j.
UInt.from_json = function (j) {
UInt.from_json = function(j) {
if (j instanceof this) {
return j.clone();
} else {
@@ -52,7 +49,7 @@ UInt.from_json = function (j) {
};
// Return a new UInt from j.
UInt.from_bits = function (j) {
UInt.from_bits = function(j) {
if (j instanceof this) {
return j.clone();
} else {
@@ -61,7 +58,16 @@ UInt.from_bits = function (j) {
};
// Return a new UInt from j.
UInt.from_bn = function (j) {
UInt.from_bytes = function(j) {
if (j instanceof this) {
return j.clone();
} else {
return (new this()).parse_bytes(j);
}
};
// Return a new UInt from j.
UInt.from_bn = function(j) {
if (j instanceof this) {
return j.clone();
} else {
@@ -69,153 +75,216 @@ UInt.from_bn = function (j) {
}
};
UInt.is_valid = function (j) {
// Return a new UInt from j.
UInt.from_number = function(j) {
if (j instanceof this) {
return j.clone();
} else {
return (new this()).parse_number(j);
}
};
UInt.is_valid = function(j) {
return this.from_json(j).is_valid();
};
UInt.prototype.clone = function () {
UInt.prototype.clone = function() {
return this.copyTo(new this.constructor());
};
// Returns copy.
UInt.prototype.copyTo = function (d) {
UInt.prototype.copyTo = function(d) {
d._value = this._value;
if (typeof d._update === 'function') {
d._update();
}
return d;
};
UInt.prototype.equals = function (d) {
UInt.prototype.equals = function(d) {
return this._value instanceof BigInteger && d._value instanceof BigInteger && this._value.equals(d._value);
};
UInt.prototype.is_valid = function () {
UInt.prototype.is_valid = function() {
return this._value instanceof BigInteger;
};
UInt.prototype.is_zero = function () {
UInt.prototype.is_zero = function() {
return this._value.equals(BigInteger.ZERO);
};
/**
* Update any derivative values.
*
* This allows subclasses to maintain caches of any data that they derive from
* the main _value. For example, the Currency class keeps the currency type, the
* currency code and other information about the currency cached.
*
* The reason for keeping this mechanism in this class is so every subclass can
* call it whenever it modifies the internal state.
*/
UInt.prototype._update = function() {
// Nothing to do by default. Subclasses will override this.
};
// value = NaN on error.
UInt.prototype.parse_generic = function (j) {
UInt.prototype.parse_generic = function(j) {
// Canonicalize and validate
if (config.accounts && j in config.accounts)
if (config.accounts && (j in config.accounts)) {
j = config.accounts[j].account;
}
switch (j) {
case undefined:
case "0":
case this.constructor.STR_ZERO:
case this.constructor.ACCOUNT_ZERO:
case this.constructor.HEX_ZERO:
this._value = nbi();
break;
case undefined:
case '0':
case this.constructor.STR_ZERO:
case this.constructor.ACCOUNT_ZERO:
case this.constructor.HEX_ZERO:
this._value = BigInteger.valueOf();
break;
case "1":
case this.constructor.STR_ONE:
case this.constructor.ACCOUNT_ONE:
case this.constructor.HEX_ONE:
this._value = new BigInteger([1]);
case '1':
case this.constructor.STR_ONE:
case this.constructor.ACCOUNT_ONE:
case this.constructor.HEX_ONE:
this._value = new BigInteger([1]);
break;
break;
default:
if ('string' !== typeof j) {
this._value = NaN;
}
else if (j[0] === "r") {
this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);
}
else if (this.constructor.width === j.length) {
this._value = new BigInteger(utils.stringToArray(j), 256);
}
else if ((this.constructor.width*2) === j.length) {
// XXX Check char set!
this._value = new BigInteger(j, 16);
}
else {
this._value = NaN;
}
default:
if (typeof j !== 'string') {
this._value = NaN;
} else if (this.constructor.width === j.length) {
this._value = new BigInteger(utils.stringToArray(j), 256);
} else if ((this.constructor.width * 2) === j.length) {
// XXX Check char set!
this._value = new BigInteger(j, 16);
} else {
this._value = NaN;
}
}
this._update();
return this;
};
UInt.prototype.parse_hex = function (j) {
if ('string' === typeof j &&
j.length === (this.constructor.width * 2)) {
this._value = new BigInteger(j, 16);
UInt.prototype.parse_hex = function(j) {
if (typeof j === 'string' && j.length === (this.constructor.width * 2)) {
this._value = new BigInteger(j, 16);
} else {
this._value = NaN;
this._value = NaN;
}
this._update();
return this;
};
UInt.prototype.parse_bits = function (j) {
UInt.prototype.parse_bits = function(j) {
if (sjcl.bitArray.bitLength(j) !== this.constructor.width * 8) {
this._value = NaN;
} else {
var bytes = sjcl.codec.bytes.fromBits(j);
this._value = new BigInteger(bytes, 256);
this.parse_bytes(bytes);
}
this._update();
return this;
};
UInt.prototype.parse_bytes = function(j) {
if (!Array.isArray(j) || j.length !== this.constructor.width) {
this._value = NaN;
} else {
this._value = new BigInteger([0].concat(j), 256);
}
this._update();
return this;
};
UInt.prototype.parse_json = UInt.prototype.parse_hex;
UInt.prototype.parse_bn = function (j) {
if (j instanceof sjcl.bn &&
j.bitLength() <= this.constructor.width * 8) {
UInt.prototype.parse_bn = function(j) {
if ((j instanceof sjcl.bn) && j.bitLength() <= this.constructor.width * 8) {
var bytes = sjcl.codec.bytes.fromBits(j.toBits());
this._value = new BigInteger(bytes, 256);
this._value = new BigInteger(bytes, 256);
} else {
this._value = NaN;
}
this._update();
return this;
};
UInt.prototype.parse_number = function(j) {
this._value = NaN;
if (typeof j === 'number' && isFinite(j) && j >= 0) {
this._value = new BigInteger(String(j));
}
this._update();
return this;
};
// Convert from internal form.
UInt.prototype.to_bytes = function () {
if (!(this._value instanceof BigInteger))
UInt.prototype.to_bytes = function() {
if (!(this._value instanceof BigInteger)) {
return null;
}
var bytes = this._value.toByteArray();
bytes = bytes.map(function (b) { return (b+256) % 256; });
bytes = bytes.map(function(b) {
return (b + 256) % 256;
});
var target = this.constructor.width;
// XXX Make sure only trim off leading zeros.
bytes = bytes.slice(-target);
while (bytes.length < target) bytes.unshift(0);
while (bytes.length < target) {
bytes.unshift(0);
}
return bytes;
};
UInt.prototype.to_hex = function () {
if (!(this._value instanceof BigInteger))
UInt.prototype.to_hex = function() {
if (!(this._value instanceof BigInteger)) {
return null;
}
var bytes = this.to_bytes();
return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(bytes)).toUpperCase();
};
UInt.prototype.to_json = UInt.prototype.to_hex;
UInt.prototype.to_bits = function () {
if (!(this._value instanceof BigInteger))
UInt.prototype.to_bits = function() {
if (!(this._value instanceof BigInteger)) {
return null;
}
var bytes = this.to_bytes();
return sjcl.codec.bytes.toBits(bytes);
};
UInt.prototype.to_bn = function () {
if (!(this._value instanceof BigInteger))
UInt.prototype.to_bn = function() {
if (!(this._value instanceof BigInteger)) {
return null;
}
var bits = this.to_bits();

23
src/js/ripple/uint128.js Normal file
View File

@@ -0,0 +1,23 @@
var utils = require('./utils');
var extend = require('extend');
var UInt = require('./uint').UInt;
//
// UInt128 support
//
var UInt128 = extend(function () {
// Internal form: NaN or BigInteger
this._value = NaN;
}, UInt);
UInt128.width = 16;
UInt128.prototype = extend({}, UInt.prototype);
UInt128.prototype.constructor = UInt128;
var HEX_ZERO = UInt128.HEX_ZERO = '00000000000000000000000000000000';
var HEX_ONE = UInt128.HEX_ONE = '00000000000000000000000000000000';
var STR_ZERO = UInt128.STR_ZERO = utils.hexToString(HEX_ZERO);
var STR_ONE = UInt128.STR_ONE = utils.hexToString(HEX_ONE);
exports.UInt128 = UInt128;

View File

@@ -1,71 +1,103 @@
var sjcl = require('../../../build/sjcl');
var utils = require('./utils');
var config = require('./config');
var jsbn = require('./jsbn');
var extend = require('extend');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var BigInteger = utils.jsbn.BigInteger;
var UInt = require('./uint').UInt,
Base = require('./base').Base;
var UInt = require('./uint').UInt;
var Base = require('./base').Base;
//
// UInt160 support
//
var UInt160 = extend(function () {
var UInt160 = extend(function() {
// Internal form: NaN or BigInteger
this._value = NaN;
this._version_byte = void(0);
this._update();
}, UInt);
UInt160.width = 20;
UInt160.prototype = extend({}, UInt.prototype);
UInt160.prototype.constructor = UInt160;
var ACCOUNT_ZERO = UInt160.ACCOUNT_ZERO = "rrrrrrrrrrrrrrrrrrrrrhoLvTp";
var ACCOUNT_ONE = UInt160.ACCOUNT_ONE = "rrrrrrrrrrrrrrrrrrrrBZbvji";
var HEX_ZERO = UInt160.HEX_ZERO = "0000000000000000000000000000000000000000";
var HEX_ONE = UInt160.HEX_ONE = "0000000000000000000000000000000000000001";
var STR_ZERO = UInt160.STR_ZERO = utils.hexToString(HEX_ZERO);
var STR_ONE = UInt160.STR_ONE = utils.hexToString(HEX_ONE);
var ACCOUNT_ZERO = UInt160.ACCOUNT_ZERO = 'rrrrrrrrrrrrrrrrrrrrrhoLvTp';
var ACCOUNT_ONE = UInt160.ACCOUNT_ONE = 'rrrrrrrrrrrrrrrrrrrrBZbvji';
var HEX_ZERO = UInt160.HEX_ZERO = '0000000000000000000000000000000000000000';
var HEX_ONE = UInt160.HEX_ONE = '0000000000000000000000000000000000000001';
var STR_ZERO = UInt160.STR_ZERO = utils.hexToString(HEX_ZERO);
var STR_ONE = UInt160.STR_ONE = utils.hexToString(HEX_ONE);
UInt160.prototype.set_version = function(j) {
this._version_byte = j;
return this;
};
UInt160.prototype.get_version = function() {
return this._version_byte;
};
// value = NaN on error.
UInt160.prototype.parse_json = function (j) {
UInt160.prototype.parse_json = function(j) {
// Canonicalize and validate
if (config.accounts && j in config.accounts)
if (config.accounts && (j in config.accounts)) {
j = config.accounts[j].account;
}
if ('number' === typeof j) {
this._value = new BigInteger(String(j));
if (typeof j === 'number' && !isNaN(j)) {
// Allow raw numbers - DEPRECATED
// This is used mostly by the test suite and is supported
// as a legacy feature only. DO NOT RELY ON THIS BEHAVIOR.
this._value = new BigInteger(String(j));
this._version_byte = Base.VER_ACCOUNT_ID;
} else if (typeof j !== 'string') {
this._value = NaN;
} else if (j[0] === 'r') {
this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);
this._version_byte = Base.VER_ACCOUNT_ID;
} else {
this.parse_hex(j);
}
else if ('string' !== typeof j) {
this._value = NaN;
}
else if (j[0] === "r") {
this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);
}
else {
this._value = NaN;
this._update();
return this;
};
UInt160.prototype.parse_generic = function(j) {
UInt.prototype.parse_generic.call(this, j);
if (isNaN(this._value)) {
if ((typeof j === 'string') && j[0] === 'r') {
this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);
}
}
this._update();
return this;
};
// XXX Json form should allow 0 and 1, C++ doesn't currently allow it.
UInt160.prototype.to_json = function (opts) {
UInt160.prototype.to_json = function(opts) {
opts = opts || {};
if (!(this._value instanceof BigInteger))
return NaN;
if (this._value instanceof BigInteger) {
// If this value has a type, return a Base58 encoded string.
if (typeof this._version_byte === 'number') {
var output = Base.encode_check(this._version_byte, this.to_bytes());
var output = Base.encode_check(Base.VER_ACCOUNT_ID, this.to_bytes());
if (opts.gateways && output in opts.gateways) {
output = opts.gateways[output];
}
if (opts.gateways && output in opts.gateways)
output = opts.gateways[output];
return output;
return output;
} else {
return this.to_hex();
}
}
return NaN;
};
exports.UInt160 = UInt160;

View File

@@ -1,34 +1,23 @@
var sjcl = require('../../../build/sjcl');
var utils = require('./utils');
var config = require('./config');
var jsbn = require('./jsbn');
var extend = require('extend');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var UInt = require('./uint').UInt,
Base = require('./base').Base;
var utils = require('./utils');
var extend = require('extend');
var UInt = require('./uint').UInt;
//
// UInt256 support
//
var UInt256 = extend(function () {
var UInt256 = extend(function() {
// Internal form: NaN or BigInteger
this._value = NaN;
this._value = NaN;
}, UInt);
UInt256.width = 32;
UInt256.prototype = extend({}, UInt.prototype);
UInt256.prototype.constructor = UInt256;
var HEX_ZERO = UInt256.HEX_ZERO = "00000000000000000000000000000000" +
"00000000000000000000000000000000";
var HEX_ONE = UInt256.HEX_ONE = "00000000000000000000000000000000" +
"00000000000000000000000000000001";
var STR_ZERO = UInt256.STR_ZERO = utils.hexToString(HEX_ZERO);
var STR_ONE = UInt256.STR_ONE = utils.hexToString(HEX_ONE);
var HEX_ZERO = UInt256.HEX_ZERO = '00000000000000000000000000000000' + '00000000000000000000000000000000';
var HEX_ONE = UInt256.HEX_ONE = '00000000000000000000000000000000' + '00000000000000000000000000000001';
var STR_ZERO = UInt256.STR_ZERO = utils.hexToString(HEX_ZERO);
var STR_ONE = UInt256.STR_ONE = utils.hexToString(HEX_ONE);
exports.UInt256 = UInt256;

View File

@@ -1,114 +1,113 @@
Function.prototype.method = function(name,func) {
this.prototype[name] = func;
return this;
};
var filterErr = function(code, done) {
function filterErr(code, done) {
return function(e) {
done(e.code !== code ? e : undefined);
};
done(e.code !== code ? e : void(0));
};
};
var throwErr = function(done) {
function throwErr(done) {
return function(e) {
if (e)
throw e;
done();
};
if (e) {
throw e;
}
done();
};
};
var trace = function(comment, func) {
function trace(comment, func) {
return function() {
console.log("%s: %s", trace, arguments.toString);
func(arguments);
};
console.log('%s: %s', trace, arguments.toString);
func(arguments);
};
};
var arraySet = function (count, value) {
var i, a = new Array(count);
function arraySet(count, value) {
var a = new Array(count);
for (i = 0; i < count; i++) {
for (var i=0; i<count; i++) {
a[i] = value;
}
return a;
};
var hexToString = function (h) {
var a = [];
var i = 0;
function hexToString(h) {
var a = [];
var i = 0;
if (h.length % 2) {
a.push(String.fromCharCode(parseInt(h.substring(0, 1), 16)));
i = 1;
}
for (; i != h.length; i += 2) {
for (; i<h.length; i+=2) {
a.push(String.fromCharCode(parseInt(h.substring(i, i+2), 16)));
}
return a.join("");
return a.join('');
};
var stringToHex = function (s) {
return Array.prototype.map.call(s, function (c) {
var b = c.charCodeAt(0);
return b < 16 ? "0" + b.toString(16) : b.toString(16);
}).join("");
function stringToHex(s) {
var result = '';
for (var i=0; i<s.length; i++) {
var b = s.charCodeAt(i);
result += b < 16 ? '0' + b.toString(16) : b.toString(16);
}
return result;
};
var stringToArray = function (s) {
function stringToArray(s) {
var a = new Array(s.length);
var i;
for (i = 0; i != a.length; i += 1)
for (var i=0; i<a.length; i+=1) {
a[i] = s.charCodeAt(i);
}
return a;
};
var hexToArray = function (h) {
function hexToArray(h) {
return stringToArray(hexToString(h));
}
};
var chunkString = function (str, n, leftAlign) {
function chunkString(str, n, leftAlign) {
var ret = [];
var i=0, len=str.length;
if (leftAlign) {
i = str.length % n;
if (i) ret.push(str.slice(0, i));
if (i) {
ret.push(str.slice(0, i));
}
}
for(; i < len; i += n) {
ret.push(str.slice(i, n+i));
for(; i<len; i+=n) {
ret.push(str.slice(i, n + i));
}
return ret;
};
var logObject = function (msg, obj) {
console.log(msg, JSON.stringify(obj, undefined, 2));
};
var assert = function (assertion, msg) {
function assert(assertion, msg) {
if (!assertion) {
throw new Error("Assertion failed" + (msg ? ": "+msg : "."));
throw new Error('Assertion failed' + (msg ? ': ' + msg : '.'));
}
};
/**
* Return unique values in array.
*/
var arrayUnique = function (arr) {
function arrayUnique(arr) {
var u = {}, a = [];
for (var i = 0, l = arr.length; i < l; ++i){
if (u.hasOwnProperty(arr[i])) {
for (var i=0, l=arr.length; i<l; i++){
var k = arr[i];
if (u[k]) {
continue;
}
a.push(arr[i]);
u[arr[i]] = 1;
a.push(k);
u[k] = true;
}
return a;
};
@@ -117,10 +116,28 @@ var arrayUnique = function (arr) {
*
* JavaScript timestamps are unix epoch in milliseconds.
*/
var toTimestamp = function (rpepoch) {
function toTimestamp(rpepoch) {
return (rpepoch + 0x386D4380) * 1000;
};
/**
* Convert a JavaScript timestamp or Date to a Ripple epoch.
*
* JavaScript timestamps are unix epoch in milliseconds.
*/
function fromTimestamp(rpepoch) {
if (rpepoch instanceof Date) {
rpepoch = rpepoch.getTime();
}
return Math.round(rpepoch / 1000) - 0x386D4380;
};
exports.time = {
fromRipple: toTimestamp,
toRipple: fromTimestamp
};
exports.trace = trace;
exports.arraySet = arraySet;
exports.hexToString = hexToString;
@@ -128,9 +145,14 @@ exports.hexToArray = hexToArray;
exports.stringToArray = stringToArray;
exports.stringToHex = stringToHex;
exports.chunkString = chunkString;
exports.logObject = logObject;
exports.assert = assert;
exports.arrayUnique = arrayUnique;
exports.toTimestamp = toTimestamp;
exports.fromTimestamp = fromTimestamp;
// Going up three levels is needed to escape the src-cov folder used for the
// test coverage stuff.
exports.sjcl = require('../../../build/sjcl');
exports.jsbn = require('../../../src/js/jsbn/jsbn');
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,11 +0,0 @@
var exports = module.exports = require('./utils.js');
// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
if (/MSIE/.test(navigator.userAgent)) {
console.log(msg, JSON.stringify(obj));
} else {
console.log(msg, "", obj);
}
};

View File

@@ -0,0 +1,607 @@
var async = require('async');
var blobClient = require('./blob').BlobClient;
var AuthInfo = require('./authinfo').AuthInfo;
var crypt = require('./crypt').Crypt;
var log = require('./log').sub('vault');
function VaultClient(opts) {
var self = this;
if (!opts) {
opts = { };
}
if (typeof opts === 'string') {
opts = { domain: opts };
}
this.domain = opts.domain || 'ripple.com';
this.infos = { };
};
/**
* getAuthInfo
* gets auth info for a username. returns authinfo
* even if user does not exists (with exist set to false)
* @param {string} username
* @param {function} callback
*/
VaultClient.prototype.getAuthInfo = function (username, callback) {
AuthInfo.get(this.domain, username, function(err, authInfo) {
if (err) {
return callback(err);
}
if (authInfo.version !== 3) {
return callback(new Error('This wallet is incompatible with this version of the vault-client.'));
}
if (!authInfo.pakdf) {
return callback(new Error('No settings for PAKDF in auth packet.'));
}
if (typeof authInfo.blobvault !== 'string') {
return callback(new Error('No blobvault specified in the authinfo.'));
}
callback(null, authInfo);
});
};
/**
* _deriveLoginKeys
* method designed for asnyc waterfall
*/
VaultClient.prototype._deriveLoginKeys = function (authInfo, password, callback) {
//derive login keys
crypt.derive(authInfo.pakdf, 'login', authInfo.username.toLowerCase(), password, function(err, keys) {
if (err) {
callback(err);
} else {
callback(null, authInfo, password, keys);
}
});
};
/**
* _deriveUnlockKey
* method designed for asnyc waterfall
*/
VaultClient.prototype._deriveUnlockKey = function (authInfo, password, keys, callback) {
//derive unlock key
crypt.derive(authInfo.pakdf, 'unlock', authInfo.username.toLowerCase(), password, function(err, unlock) {
if (err) {
log.error('derive:', err);
return callback(err);
}
if (!keys) {
keys = { };
}
keys.unlock = unlock.unlock;
callback(null, authInfo, keys);
});
};
/**
* Get a ripple name from a given account address, if it has one
* @param {string} address - Account address to query
* @param {string} url - Url of blob vault
*/
VaultClient.prototype.getRippleName = function(address, url, callback) {
//use the url from previously retrieved authInfo, if necessary
if (!url) {
callback(new Error('Blob vault URL is required'));
} else {
blobClient.getRippleName(url, address, callback);
}
};
/**
* Check blobvault for existance of username
*
* @param {string} username
* @param {function} fn - Callback function
*/
VaultClient.prototype.exists = function(username, callback) {
AuthInfo.get(this.domain, username.toLowerCase(), function(err, authInfo) {
if (err) {
callback(err);
} else {
callback(null, !!authInfo.exists);
}
});
};
/**
* Authenticate and retrieve a decrypted blob using a ripple name and password
*
* @param {string} username
* @param {string} password
* @param {function} fn - Callback function
*/
VaultClient.prototype.login = function(username, password, callback) {
var self = this;
var steps = [
getAuthInfo,
self._deriveLoginKeys,
getBlob
];
async.waterfall(steps, callback);
function getAuthInfo(callback) {
self.getAuthInfo(username, function(err, authInfo){
if (authInfo && !authInfo.exists) {
return callback(new Error('User does not exist.'));
}
return callback (err, authInfo, password);
});
}
function getBlob(authInfo, password, keys, callback) {
blobClient.get(authInfo.blobvault, keys.id, keys.crypt, function(err, blob) {
if (err) {
return callback(err);
}
//save for relogin
self.infos[keys.id] = authInfo;
//migrate missing fields
if (blob.missing_fields) {
if (blob.missing_fields.encrypted_blobdecrypt_key) {
log.info('migration: saving encrypted blob decrypt key');
authInfo.blob = blob;
//get the key to unlock the secret, then update the blob keys
self._deriveUnlockKey(authInfo, password, keys, updateKeys);
}
}
callback(null, {
blob : blob,
username : authInfo.username,
verified : authInfo.emailVerified
});
});
};
function updateKeys (err, params, keys) {
if (err || !keys.unlock) {
return; //unable to unlock
}
var secret;
try {
secret = crypt.decrypt(keys.unlock, params.blob.encrypted_secret);
} catch (error) {
return log.error('decrypt:', error);
}
options = {
username : params.username,
blob : params.blob,
masterkey : secret,
keys : keys
};
blobClient.updateKeys(options, function(err, resp){
if (err) {
log.error('updateKeys:', err);
}
});
}
};
/**
* Retreive and decrypt blob using a blob url, id and crypt derived previously.
*
* @param {string} url - Blob vault url
* @param {string} id - Blob id from previously retreived blob
* @param {string} key - Blob decryption key
* @param {function} fn - Callback function
*/
VaultClient.prototype.relogin = function(url, id, key, callback) {
//use the url from previously retrieved authInfo, if necessary
if (!url && this.infos[id]) {
url = this.infos[id].blobvault;
}
if (!url) {
return callback(new Error('Blob vault URL is required'));
}
blobClient.get(url, id, key, function(err, blob) {
if (err) {
callback(err);
} else {
callback (null, { blob: blob });
}
});
};
/**
* Decrypt the secret key using a username and password
*
* @param {string} username
* @param {string} password
* @param {string} encryptSecret
* @param {function} fn - Callback function
*/
VaultClient.prototype.unlock = function(username, password, encryptSecret, fn) {
var self = this;
var steps = [
getAuthInfo,
self._deriveUnlockKey,
unlockSecret
];
async.waterfall(steps, fn);
function getAuthInfo(callback) {
self.getAuthInfo(username, function(err, authInfo){
if (authInfo && !authInfo.exists) {
return callback(new Error('User does not exist.'));
}
return callback (err, authInfo, password, {});
});
}
function unlockSecret (authinfo, keys, callback) {
var secret;
try {
secret = crypt.decrypt(keys.unlock, encryptSecret);
} catch (error) {
return callback(error);
}
callback(null, {
keys : keys,
secret : secret
});
}
};
/**
* Retrieve the decrypted blob and secret key in one step using
* the username and password
*
* @param {string} username
* @param {string} password
* @param {function} fn - Callback function
*/
VaultClient.prototype.loginAndUnlock = function(username, password, fn) {
var self = this;
var steps = [
login,
deriveUnlockKey,
unlockSecret
];
async.waterfall(steps, fn);
function login (callback) {
self.login(username, password, function(err, resp) {
if (err) {
return callback(err);
}
if (!resp.blob || !resp.blob.encrypted_secret) {
return callback(new Error('Unable to retrieve blob and secret.'));
}
if (!resp.blob.id || !resp.blob.key) {
return callback(new Error('Unable to retrieve keys.'));
}
//get authInfo via id - would have been saved from login
var authInfo = self.infos[resp.blob.id];
if (!authInfo) {
return callback(new Error('Unable to find authInfo'));
}
callback(null, authInfo, password, resp.blob);
});
};
function deriveUnlockKey (authInfo, password, blob, callback) {
self._deriveUnlockKey(authInfo, password, null, function(err, authInfo, keys){
callback(err, keys.unlock, authInfo, blob);
});
};
function unlockSecret (unlock, authInfo, blob, callback) {
var secret;
try {
secret = crypt.decrypt(unlock, blob.encrypted_secret);
} catch (error) {
return callback(error);
}
callback(null, {
blob : blob,
unlock : unlock,
secret : secret,
username : authInfo.username,
verified : authInfo.emailVerified
});
};
};
/**
* Verify an email address for an existing user
*
* @param {string} username
* @param {string} token - Verification token
* @param {function} fn - Callback function
*/
VaultClient.prototype.verify = function(username, token, callback) {
var self = this;
self.getAuthInfo(username, function (err, authInfo){
if (err) {
return callback(err);
}
blobClient.verify(authInfo.blobvault, username.toLowerCase(), token, callback);
});
};
/**
* resendEmail
* send a new verification email
* @param {object} options
* @param {string} options.id
* @param {string} options.username
* @param {string} options.account_id
* @param {string} options.email
* @param {string} options.activateLink
* @param {function} fn - Callback
*/
VaultClient.prototype.resendEmail = function (options, fn) {
blobClient.resendEmail(options, fn);
};
/**
* deleteBlob
* @param {object} options
* @param {string} options.url
* @param {string} options.username
* @param {string} options.blob_id
* @param {string} options.account_id
* @param {string} options.masterkey
*/
VaultClient.prototype.deleteBlob = function (options, fn) {
blobClient.deleteBlob(options, fn);
};
/**
* updateProfile
* update information stored outside the blob
* @param {object}
* @param {string} options.url
* @param {string} options.username
* @param {string} options.auth_secret
* @param {srring} options.blob_id
* @param {object} options.profile
* @param {string} options.profile.phone - optional
* @param {string} options.profile.country - optional
* @param {string} options.profile.region - optional
* @param {string} options.profile.city - optional
*/
VaultClient.prototype.updateProfile = function (options, fn) {
blobClient.updateProfile(options, fn);
};
/**
* recoverBlob
* recover blob with account secret
* @param {object} options
* @param {string} options.url
* @param {string} options.username
* @param {string} options.masterkey
* @param {function}
*/
VaultClient.prototype.recoverBlob = function (options, fn) {
blobClient.recoverBlob(options, fn);
};
/*
* changePassword
* @param {object} options
* @param {string} options.username
* @param {string} options.password
* @param {string} options.masterkey
* @param {object} options.blob
*/
VaultClient.prototype.changePassword = function (options, fn) {
var self = this;
var password = String(options.password).trim();
var steps = [
getAuthInfo,
self._deriveLoginKeys,
self._deriveUnlockKey,
changePassword
];
async.waterfall(steps, fn);
function getAuthInfo(callback) {
self.getAuthInfo(options.username, function(err, authInfo) {
return callback (err, authInfo, password);
});
};
function changePassword (authInfo, keys, callback) {
options.keys = keys;
blobClient.updateKeys(options, callback);
};
};
/**
* rename
* rename a ripple account
* @param {object} options
* @param {string} options.username
* @param {string} options.new_username
* @param {string} options.password
* @param {string} options.masterkey
* @param {object} options.blob
* @param {function} fn
*/
VaultClient.prototype.rename = function (options, fn) {
var self = this;
var new_username = String(options.new_username).trim();
var password = String(options.password).trim();
var steps = [
getAuthInfo,
self._deriveLoginKeys,
self._deriveUnlockKey,
renameBlob
];
async.waterfall(steps, fn);
function getAuthInfo(callback) {
self.getAuthInfo(new_username, function(err, authInfo){
if (authInfo && authInfo.exists) {
return callback(new Error('username already taken.'));
} else {
authInfo.username = new_username;
}
return callback (err, authInfo, password);
});
};
function renameBlob (authInfo, keys, callback) {
options.keys = keys;
blobClient.rename(options, callback);
};
};
/**
* Register a new user and save to the blob vault
*
* @param {object} options
* @param {string} options.username
* @param {string} options.password
* @param {string} options.masterkey //optional, will create if absent
* @param {string} options.email
* @param {string} options.activateLink
* @param {object} options.oldUserBlob //optional
* @param {function} fn
*/
VaultClient.prototype.register = function(options, fn) {
var self = this;
var username = String(options.username).trim();
var password = String(options.password).trim();
var result = self.validateUsername(username);
if (!result.valid) {
return fn(new Error('invalid username.'));
}
var steps = [
getAuthInfo,
self._deriveLoginKeys,
self._deriveUnlockKey,
create
];
async.waterfall(steps, fn);
function getAuthInfo(callback) {
self.getAuthInfo(username, function(err, authInfo){
return callback (err, authInfo, password);
});
};
function create(authInfo, keys, callback) {
var params = {
url : authInfo.blobvault,
id : keys.id,
crypt : keys.crypt,
unlock : keys.unlock,
username : username,
email : options.email,
masterkey : options.masterkey || crypt.createMaster(),
activateLink : options.activateLink,
oldUserBlob : options.oldUserBlob,
domain : options.domain
};
blobClient.create(params, function(err, blob) {
if (err) {
callback(err);
} else {
callback(null, {
blob : blob,
username : username
});
}
});
};
};
VaultClient.prototype.validateUsername = function (username) {
username = String(username).trim();
var result = {
valid : false,
reason : ''
};
if (username.length < 2) {
result.reason = 'tooshort';
} else if (username.length > 20) {
result.reason = 'toolong';
} else if (!/^[a-zA-Z0-9\-]+$/.exec(username)) {
result.reason = 'charset';
} else if (/^-/.exec(username)) {
result.reason = 'starthyphen';
} else if (/-$/.exec(username)) {
result.reason = 'endhyphen';
} else if (/--/.exec(username)) {
result.reason = 'multhyphen';
} else {
result.valid = true;
}
return result;
};
exports.VaultClient = VaultClient;

View File

@@ -0,0 +1,83 @@
/**
* Check that the point is valid based on the method described in
* SEC 1: Elliptic Curve Cryptography, section 3.2.2.1:
* Elliptic Curve Public Key Validation Primitive
* http://www.secg.org/download/aid-780/sec1-v2.pdf
*
* @returns {Boolean}
*/
sjcl.ecc.point.prototype.isValidPoint = function() {
var self = this;
var field_modulus = self.curve.field.modulus;
if (self.isIdentity) {
return false;
}
// Check that coordinatres are in bounds
// Return false if x < 1 or x > (field_modulus - 1)
if (((new sjcl.bn(1).greaterEquals(self.x)) &&
!self.x.equals(1)) ||
(self.x.greaterEquals(field_modulus.sub(1))) &&
!self.x.equals(1)) {
return false;
}
// Return false if y < 1 or y > (field_modulus - 1)
if (((new sjcl.bn(1).greaterEquals(self.y)) &&
!self.y.equals(1)) ||
(self.y.greaterEquals(field_modulus.sub(1))) &&
!self.y.equals(1)) {
return false;
}
if (!self.isOnCurve()) {
return false;
}
// TODO check to make sure point is a scalar multiple of base_point
return true;
};
/**
* Check that the point is on the curve
*
* @returns {Boolean}
*/
sjcl.ecc.point.prototype.isOnCurve = function() {
var self = this;
var field_order = self.curve.r;
var component_a = self.curve.a;
var component_b = self.curve.b;
var field_modulus = self.curve.field.modulus;
var left_hand_side = self.y.mul(self.y).mod(field_modulus);
var right_hand_side = self.x.mul(self.x).mul(self.x).add(component_a.mul(self.x)).add(component_b).mod(field_modulus);
return left_hand_side.equals(right_hand_side);
};
sjcl.ecc.point.prototype.toString = function() {
return '(' +
this.x.toString() + ', ' +
this.y.toString() +
')';
};
sjcl.ecc.pointJac.prototype.toString = function() {
return '(' +
this.x.toString() + ', ' +
this.y.toString() + ', ' +
this.z.toString() +
')';
};

View File

@@ -0,0 +1,17 @@
sjcl.ecc.ecdsa.secretKey.prototype.canonicalizeSignature = function(rs) {
var w = sjcl.bitArray,
R = this._curve.r,
l = R.bitLength();
var r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l));
// For a canonical signature we want the lower of two possible values for s
// 0 < s <= n/2
if (!R.copy().halveM().greaterEquals(s)) {
s = R.sub(s);
}
return w.concat(r.toBits(l), s.toBits(l));
};

View File

@@ -0,0 +1,306 @@
/**
* This module uses the public key recovery method
* described in SEC 1: Elliptic Curve Cryptography,
* section 4.1.6, "Public Key Recovery Operation".
* http://www.secg.org/download/aid-780/sec1-v2.pdf
*
* Implementation based on:
* https://github.com/bitcoinjs/bitcoinjs-lib/blob/89cf731ac7309b4f98994e3b4b67b7226020181f/src/ecdsa.js
*/
// Defined here so that this value only needs to be calculated once
var FIELD_MODULUS_PLUS_ONE_DIVIDED_BY_FOUR;
/**
* Sign the given hash such that the public key, prepending an extra byte
* so that the public key will be recoverable from the signature
*
* @param {bitArray} hash
* @param {Number} paranoia
* @returns {bitArray} Signature formatted as bitArray
*/
sjcl.ecc.ecdsa.secretKey.prototype.signWithRecoverablePublicKey = function(hash, paranoia, k_for_testing) {
var self = this;
// Convert hash to bits and determine encoding for output
var hash_bits;
if (typeof hash === 'object' && hash.length > 0 && typeof hash[0] === 'number') {
hash_bits = hash;
} else {
throw new sjcl.exception.invalid('hash. Must be a bitArray');
}
// Sign hash with standard, canonicalized method
var standard_signature = self.sign(hash_bits, paranoia, k_for_testing);
var canonical_signature = self.canonicalizeSignature(standard_signature);
// Extract r and s signature components from canonical signature
var r_and_s = getRandSFromSignature(self._curve, canonical_signature);
// Rederive public key
var public_key = self._curve.G.mult(sjcl.bn.fromBits(self.get()));
// Determine recovery factor based on which possible value
// returns the correct public key
var recovery_factor = calculateRecoveryFactor(self._curve, r_and_s.r, r_and_s.s, hash_bits, public_key);
// Prepend recovery_factor to signature and encode in DER
// The value_to_prepend should be 4 bytes total
var value_to_prepend = recovery_factor + 27;
var final_signature_bits = sjcl.bitArray.concat([value_to_prepend], canonical_signature);
// Return value in bits
return final_signature_bits;
};
/**
* Recover the public key from a signature created with the
* signWithRecoverablePublicKey method in this module
*
* @static
*
* @param {bitArray} hash
* @param {bitArray} signature
* @param {sjcl.ecc.curve} [sjcl.ecc.curves['c256']] curve
* @returns {sjcl.ecc.ecdsa.publicKey} Public key
*/
sjcl.ecc.ecdsa.publicKey.recoverFromSignature = function(hash, signature, curve) {
if (!signature || signature instanceof sjcl.ecc.curve) {
throw new sjcl.exception.invalid('must supply hash and signature to recover public key');
}
if (!curve) {
curve = sjcl.ecc.curves['c256'];
}
// Convert hash to bits and determine encoding for output
var hash_bits;
if (typeof hash === 'object' && hash.length > 0 && typeof hash[0] === 'number') {
hash_bits = hash;
} else {
throw new sjcl.exception.invalid('hash. Must be a bitArray');
}
var signature_bits;
if (typeof signature === 'object' && signature.length > 0 && typeof signature[0] === 'number') {
signature_bits = signature;
} else {
throw new sjcl.exception.invalid('signature. Must be a bitArray');
}
// Extract recovery_factor from first 4 bytes
var recovery_factor = signature_bits[0] - 27;
if (recovery_factor < 0 || recovery_factor > 3) {
throw new sjcl.exception.invalid('signature. Signature must be generated with algorithm ' +
'that prepends the recovery factor in order to recover the public key');
}
// Separate r and s values
var r_and_s = getRandSFromSignature(curve, signature_bits.slice(1));
var signature_r = r_and_s.r;
var signature_s = r_and_s.s;
// Recover public key using recovery_factor
var recovered_public_key_point = recoverPublicKeyPointFromSignature(curve, signature_r, signature_s, hash_bits, recovery_factor);
var recovered_public_key = new sjcl.ecc.ecdsa.publicKey(curve, recovered_public_key_point);
return recovered_public_key;
};
/**
* Retrieve the r and s components of a signature
*
* @param {sjcl.ecc.curve} curve
* @param {bitArray} signature
* @returns {Object} Object with 'r' and 's' fields each as an sjcl.bn
*/
function getRandSFromSignature(curve, signature) {
var r_length = curve.r.bitLength();
return {
r: sjcl.bn.fromBits(sjcl.bitArray.bitSlice(signature, 0, r_length)),
s: sjcl.bn.fromBits(sjcl.bitArray.bitSlice(signature, r_length, sjcl.bitArray.bitLength(signature)))
};
};
/**
* Determine the recovery factor by trying all four
* possibilities and figuring out which results in the
* correct public key
*
* @param {sjcl.ecc.curve} curve
* @param {sjcl.bn} r
* @param {sjcl.bn} s
* @param {bitArray} hash_bits
* @param {sjcl.ecc.point} original_public_key_point
* @returns {Number, 0-3} Recovery factor
*/
function calculateRecoveryFactor(curve, r, s, hash_bits, original_public_key_point) {
var original_public_key_point_bits = original_public_key_point.toBits();
// TODO: verify that it is possible for the recovery_factor to be 2 or 3,
// we may only need 1 bit because the canonical signature might remove the
// possibility of us needing to "use the second candidate key"
for (var possible_factor = 0; possible_factor < 4; possible_factor++) {
var resulting_public_key_point;
try {
resulting_public_key_point = recoverPublicKeyPointFromSignature(curve, r, s, hash_bits, possible_factor);
} catch (err) {
// console.log(err, err.stack);
continue;
}
if (sjcl.bitArray.equal(resulting_public_key_point.toBits(), original_public_key_point_bits)) {
return possible_factor;
}
}
throw new sjcl.exception.bug('unable to calculate recovery factor from signature');
};
/**
* Recover the public key from the signature.
*
* @param {sjcl.ecc.curve} curve
* @param {sjcl.bn} r
* @param {sjcl.bn} s
* @param {bitArray} hash_bits
* @param {Number, 0-3} recovery_factor
* @returns {sjcl.point} Public key corresponding to signature
*/
function recoverPublicKeyPointFromSignature(curve, signature_r, signature_s, hash_bits, recovery_factor) {
var field_order = curve.r;
var field_modulus = curve.field.modulus;
// Reduce the recovery_factor to the two bits used
recovery_factor = recovery_factor & 3;
// The less significant bit specifies whether the y coordinate
// of the compressed point is even or not.
var compressed_point_y_coord_is_even = recovery_factor & 1;
// The more significant bit specifies whether we should use the
// first or second candidate key.
var use_second_candidate_key = recovery_factor >> 1;
// Calculate (field_order + 1) / 4
if (!FIELD_MODULUS_PLUS_ONE_DIVIDED_BY_FOUR) {
FIELD_MODULUS_PLUS_ONE_DIVIDED_BY_FOUR = field_modulus.add(1).div(4);
}
// In the paper they write "1. For j from 0 to h do the following..."
// That is not necessary here because we are given the recovery_factor
// step 1.1 Let x = r + jn
// Here "j" is either 0 or 1
var x;
if (use_second_candidate_key) {
x = signature_r.add(field_order);
} else {
x = signature_r;
}
// step 1.2 and 1.3 convert x to an elliptic curve point
// Following formula in section 2.3.4 Octet-String-to-Elliptic-Curve-Point Conversion
var alpha = x.mul(x).mul(x).add(curve.a.mul(x)).add(curve.b).mod(field_modulus);
var beta = alpha.powermodMontgomery(FIELD_MODULUS_PLUS_ONE_DIVIDED_BY_FOUR, field_modulus);
// If beta is even but y isn't or
// if beta is odd and y is even
// then subtract beta from the field_modulus
var y;
var beta_is_even = beta.mod(2).equals(0);
if (beta_is_even && !compressed_point_y_coord_is_even ||
!beta_is_even && compressed_point_y_coord_is_even) {
y = beta;
} else {
y = field_modulus.sub(beta);
}
// generated_point_R is the point generated from x and y
var generated_point_R = new sjcl.ecc.point(curve, x, y);
// step 1.4 check that R is valid and R x field_order !== infinity
// TODO: add check for R x field_order === infinity
if (!generated_point_R.isValidPoint()) {
throw new sjcl.exception.corrupt('point R. Not a valid point on the curve. Cannot recover public key');
}
// step 1.5 Compute e from M
var message_e = sjcl.bn.fromBits(hash_bits);
var message_e_neg = new sjcl.bn(0).sub(message_e).mod(field_order);
// step 1.6 Compute Q = r^-1 (sR - eG)
// console.log('r: ', signature_r);
var signature_r_inv = signature_r.inverseMod(field_order);
var public_key_point = generated_point_R.mult2(signature_s, message_e_neg, curve.G).mult(signature_r_inv);
// Validate public key point
if (!public_key_point.isValidPoint()) {
throw new sjcl.exception.corrupt('public_key_point. Not a valid point on the curve. Cannot recover public key');
}
// Verify that this public key matches the signature
if (!verify_raw(curve, message_e, signature_r, signature_s, public_key_point)) {
throw new sjcl.exception.corrupt('cannot recover public key');
}
return public_key_point;
};
/**
* Verify a signature given the raw components
* using method defined in section 4.1.5:
* "Alternative Verifying Operation"
*
* @param {sjcl.ecc.curve} curve
* @param {sjcl.bn} e
* @param {sjcl.bn} r
* @param {sjcl.bn} s
* @param {sjcl.ecc.point} public_key_point
* @returns {Boolean}
*/
function verify_raw(curve, e, r, s, public_key_point) {
var field_order = curve.r;
// Return false if r is out of bounds
if ((new sjcl.bn(1)).greaterEquals(r) || r.greaterEquals(new sjcl.bn(field_order))) {
return false;
}
// Return false if s is out of bounds
if ((new sjcl.bn(1)).greaterEquals(s) || s.greaterEquals(new sjcl.bn(field_order))) {
return false;
}
// Check that r = (u1 + u2)G
// u1 = e x s^-1 (mod field_order)
// u2 = r x s^-1 (mod field_order)
var s_mod_inverse_field_order = s.inverseMod(field_order);
var u1 = e.mul(s_mod_inverse_field_order).mod(field_order);
var u2 = r.mul(s_mod_inverse_field_order).mod(field_order);
var point_computed = curve.G.mult2(u1, u2, public_key_point);
return r.equals(point_computed.x.mod(field_order));
};

View File

@@ -6,11 +6,9 @@ sjcl.bn.prototype.divRem = function (that) {
var thisa = this.abs(), thata = that.abs(), quot = new this._class(0),
ci = 0;
if (!thisa.greaterEquals(thata)) {
this.initWith(0);
return this;
return [new sjcl.bn(0), this.copy()];
} else if (thisa.equals(thata)) {
this.initWith(1);
return this;
return [new sjcl.bn(1), new sjcl.bn(0)];
}
for (; thisa.greaterEquals(thata); ci++) {
@@ -45,8 +43,8 @@ sjcl.bn.prototype.div = function (that) {
};
sjcl.bn.prototype.sign = function () {
return this.greaterEquals(sjcl.bn.ZERO) ? 1 : -1;
};
return this.greaterEquals(sjcl.bn.ZERO) ? 1 : -1;
};
/** -this */
sjcl.bn.prototype.neg = function () {
@@ -59,3 +57,89 @@ sjcl.bn.prototype.abs = function () {
return this.neg();
} else return this;
};
/** this >> that */
sjcl.bn.prototype.shiftRight = function (that) {
if ("number" !== typeof that) {
throw new Error("shiftRight expects a number");
}
that = +that;
if (that < 0) {
return this.shiftLeft(that);
}
var a = new sjcl.bn(this);
while (that >= this.radix) {
a.limbs.shift();
that -= this.radix;
}
while (that--) {
a.halveM();
}
return a;
};
/** this >> that */
sjcl.bn.prototype.shiftLeft = function (that) {
if ("number" !== typeof that) {
throw new Error("shiftLeft expects a number");
}
that = +that;
if (that < 0) {
return this.shiftRight(that);
}
var a = new sjcl.bn(this);
while (that >= this.radix) {
a.limbs.unshift(0);
that -= this.radix;
}
while (that--) {
a.doubleM();
}
return a;
};
/** (int)this */
// NOTE Truncates to 32-bit integer
sjcl.bn.prototype.toNumber = function () {
return this.limbs[0] | 0;
};
/** find n-th bit, 0 = LSB */
sjcl.bn.prototype.testBit = function (bitIndex) {
var limbIndex = Math.floor(bitIndex / this.radix);
var bitIndexInLimb = bitIndex % this.radix;
if (limbIndex >= this.limbs.length) return 0;
return (this.limbs[limbIndex] >>> bitIndexInLimb) & 1;
};
/** set n-th bit, 0 = LSB */
sjcl.bn.prototype.setBitM = function (bitIndex) {
var limbIndex = Math.floor(bitIndex / this.radix);
var bitIndexInLimb = bitIndex % this.radix;
while (limbIndex >= this.limbs.length) this.limbs.push(0);
this.limbs[limbIndex] |= 1 << bitIndexInLimb;
this.cnormalize();
return this;
};
sjcl.bn.prototype.modInt = function (n) {
return this.toNumber() % n;
};

View File

@@ -0,0 +1,45 @@
sjcl.bn.prototype.jacobi = function (that) {
var a = this;
that = new sjcl.bn(that);
if (that.sign() === -1) return;
// 1. If a = 0 then return(0).
if (a.equals(0)) { return 0; }
// 2. If a = 1 then return(1).
if (a.equals(1)) { return 1; }
var s = 0;
// 3. Write a = 2^e * a1, where a1 is odd.
var e = 0;
while (!a.testBit(e)) e++;
var a1 = a.shiftRight(e);
// 4. If e is even then set s ← 1.
if ((e & 1) === 0) {
s = 1;
} else {
var residue = that.modInt(8);
if (residue === 1 || residue === 7) {
// Otherwise set s ← 1 if n ≡ 1 or 7 (mod 8)
s = 1;
} else if (residue === 3 || residue === 5) {
// Or set s ← 1 if n ≡ 3 or 5 (mod 8).
s = -1;
}
}
// 5. If n ≡ 3 (mod 4) and a1 ≡ 3 (mod 4) then set s ← s.
if (that.modInt(4) === 3 && a1.modInt(4) === 3) {
s = -s;
}
if (a1.equals(1)) {
return s;
} else {
return s * that.mod(a1).jacobi(a1);
}
};

View File

@@ -0,0 +1,156 @@
sjcl.bn.prototype.invDigit = function ()
{
var radixMod = 1 + this.radixMask;
if (this.limbs.length < 1) return 0;
var x = this.limbs[0];
if ((x&1) == 0) return 0;
var y = x&3; // y == 1/x mod 2^2
y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
// last step - calculate inverse mod DV directly;
// assumes 16 < radixMod <= 32 and assumes ability to handle 48-bit ints
y = (y*(2-x*y%radixMod))%radixMod; // y == 1/x mod 2^dbits
// we really want the negative inverse, and -DV < y < DV
return (y>0)?radixMod-y:-y;
};
// returns bit length of the integer x
function nbits(x) {
var r = 1, t;
if((t=x>>>16) != 0) { x = t; r += 16; }
if((t=x>>8) != 0) { x = t; r += 8; }
if((t=x>>4) != 0) { x = t; r += 4; }
if((t=x>>2) != 0) { x = t; r += 2; }
if((t=x>>1) != 0) { x = t; r += 1; }
return r;
}
// JSBN-style add and multiply for SJCL w/ 24 bit radix
sjcl.bn.prototype.am = function (i,x,w,j,c,n) {
var xl = x&0xfff, xh = x>>12;
while (--n >= 0) {
var l = this.limbs[i]&0xfff;
var h = this.limbs[i++]>>12;
var m = xh*l+h*xl;
l = xl*l+((m&0xfff)<<12)+w.limbs[j]+c;
c = (l>>24)+(m>>12)+xh*h;
w.limbs[j++] = l&0xffffff;
}
return c;
}
var Montgomery = function (m)
{
this.m = m;
this.mt = m.limbs.length;
this.mt2 = this.mt * 2;
this.mp = m.invDigit();
this.mpl = this.mp&0x7fff;
this.mph = this.mp>>15;
this.um = (1<<(m.radix-15))-1;
};
Montgomery.prototype.reduce = function (x)
{
var radixMod = x.radixMask + 1;
while (x.limbs.length <= this.mt2) // pad x so am has enough room later
x.limbs[x.limbs.length] = 0;
for (var i = 0; i < this.mt; ++i) {
// faster way of calculating u0 = x[i]*mp mod 2^radix
var j = x.limbs[i]&0x7fff;
var u0 = (j*this.mpl+(((j*this.mph+(x.limbs[i]>>15)*this.mpl)&this.um)<<15))&x.radixMask;
// use am to combine the multiply-shift-add into one call
j = i+this.mt;
x.limbs[j] += this.m.am(0,u0,x,i,0,this.mt);
// propagate carry
while (x.limbs[j] >= radixMod) { x.limbs[j] -= radixMod; x.limbs[++j]++; }
}
x.trim();
x = x.shiftRight(this.mt * this.m.radix);
if (x.greaterEquals(this.m)) x = x.sub(this.m);
return x.trim().normalize().reduce();
};
Montgomery.prototype.square = function (x)
{
return this.reduce(x.square());
};
Montgomery.prototype.multiply = function (x, y)
{
return this.reduce(x.mul(y));
};
Montgomery.prototype.convert = function (x)
{
return x.abs().shiftLeft(this.mt * this.m.radix).mod(this.m);
};
Montgomery.prototype.revert = function (x)
{
return this.reduce(x.copy());
};
sjcl.bn.prototype.powermodMontgomery = function (e, m)
{
var i = e.bitLength(), k, r = new this._class(1);
if (i <= 0) return r;
else if (i < 18) k = 1;
else if (i < 48) k = 3;
else if (i < 144) k = 4;
else if (i < 768) k = 5;
else k = 6;
if (i < 8 || !m.testBit(0)) {
// For small exponents and even moduli, use a simple square-and-multiply
// algorithm.
return this.powermod(e, m);
}
var z = new Montgomery(m);
e.trim().normalize();
// precomputation
var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
g[1] = z.convert(this);
if (k > 1) {
var g2 = z.square(g[1]);
while (n <= km) {
g[n] = z.multiply(g2, g[n-2]);
n += 2;
}
}
var j = e.limbs.length-1, w, is1 = true, r2 = new this._class(), t;
i = nbits(e.limbs[j])-1;
while (j >= 0) {
if (i >= k1) w = (e.limbs[j]>>(i-k1))&km;
else {
w = (e.limbs[j]&((1<<(i+1))-1))<<(k1-i);
if (j > 0) w |= e.limbs[j-1]>>(this.radix+i-k1);
}
n = k;
while ((w&1) == 0) { w >>= 1; --n; }
if ((i -= n) < 0) { i += this.radix; --j; }
if (is1) { // ret == 1, don't bother squaring or multiplying it
r = g[w].copy();
is1 = false;
} else {
while (n > 1) { r2 = z.square(r); r = z.square(r2); n -= 2; }
if (n > 0) r2 = z.square(r); else { t = r; r = r2; r2 = t; }
r = z.multiply(r2,g[w]);
}
while (j >= 0 && (e.limbs[j]&(1<<i)) == 0) {
r2 = z.square(r); t = r; r = r2; r2 = t;
if (--i < 0) { i = this.radix-1; --j; }
}
}
return z.revert(r);
}

View File

@@ -1,6 +1,6 @@
// ----- for secp256k1 ------
// Overwrite NIST-P256 with secp256k1 so we're on even footing
// Overwrite NIST-P256 with secp256k1
sjcl.ecc.curves.c256 = new sjcl.ecc.curve(
sjcl.bn.pseudoMersennePrime(256, [[0,-1],[4,-1],[6,-1],[7,-1],[8,-1],[9,-1],[32,-1]]),
"0x14551231950b75fc4402da1722fc9baee",
@@ -62,7 +62,7 @@ sjcl.ecc.pointJac.prototype.doubl = function () {
var f = e.square();
var x = f.sub(d.copy().doubleM());
var y = e.mul(d.sub(x)).subM(c.doubleM().doubleM().doubleM());
var z = this.y.mul(this.z).doubleM();
var z = this.z.mul(this.y).doubleM();
return new sjcl.ecc.pointJac(this.curve, x, y, z);
};

View File

@@ -1,30 +1,38 @@
sjcl.ecc.ecdsa.secretKey.prototype = {
sign: function(hash, paranoia) {
var R = this._curve.r,
l = R.bitLength(),
k = sjcl.bn.random(R.sub(1), paranoia).add(1),
r = this._curve.G.mult(k).x.mod(R),
s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).mul(k.inverseMod(R)).mod(R);
sjcl.ecc.ecdsa.secretKey.prototype.sign = function(hash, paranoia, k_for_testing) {
var R = this._curve.r,
l = R.bitLength();
return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
// k_for_testing should ONLY BE SPECIFIED FOR TESTING
// specifying it will make the signature INSECURE
var k;
if (typeof k_for_testing === 'object' && k_for_testing.length > 0 && typeof k_for_testing[0] === 'number') {
k = k_for_testing;
} else if (typeof k_for_testing === 'string' && /^[0-9a-fA-F]+$/.test(k_for_testing)) {
k = sjcl.bn.fromBits(sjcl.codec.hex.toBits(k_for_testing));
} else {
// This is the only option that should be used in production
k = sjcl.bn.random(R.sub(1), paranoia).add(1);
}
var r = this._curve.G.mult(k).x.mod(R);
var s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).mul(k.inverseMod(R)).mod(R);
return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
};
sjcl.ecc.ecdsa.publicKey.prototype = {
verify: function(hash, rs) {
var w = sjcl.bitArray,
R = this._curve.r,
l = R.bitLength(),
r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),
sInv = s.modInverse(R),
hG = sjcl.bn.fromBits(hash).mul(sInv).mod(R),
hA = r.mul(sInv).mod(R),
r2 = this._curve.G.mult2(hG, hA, this._point).x;
sjcl.ecc.ecdsa.publicKey.prototype.verify = function(hash, rs) {
var w = sjcl.bitArray,
R = this._curve.r,
l = R.bitLength(),
r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),
sInv = s.inverseMod(R),
hG = sjcl.bn.fromBits(hash).mul(sInv).mod(R),
hA = r.mul(sInv).mod(R),
r2 = this._curve.G.mult2(hG, hA, this._point).x;
if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) {
throw (new sjcl.exception.corrupt("signature didn't check out"));
}
return true;
if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) {
throw (new sjcl.exception.corrupt("signature didn't check out"));
}
return true;
};

View File

@@ -11,8 +11,16 @@ sjcl.ecc.point = function(curve,x,y) {
if (x === undefined) {
this.isIdentity = true;
} else {
if (x instanceof sjcl.bn) {
x = new curve.field(x);
}
if (y instanceof sjcl.bn) {
y = new curve.field(y);
}
this.x = x;
this.y = y;
this.isIdentity = false;
}
this.curve = curve;

181
test/account-test.js Normal file
View File

@@ -0,0 +1,181 @@
var assert = require('assert');
var Account = require('../src/js/ripple/account').Account;
describe('Account', function(){
describe('._publicKeyToAddress()', function(){
it('should throw an error if the key is invalid', function(){
try {
Account._publicKeyToAddress('not a real key');
} catch (e) {
assert(e);
}
});
it('should return unchanged a valid UINT160', function(){
assert('rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz' === Account._publicKeyToAddress('rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz'));
});
it('should parse a hex-encoded public key as a UINT160', function(){
assert('rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz' === Account._publicKeyToAddress('025B32A54BFA33FB781581F49B235C0E2820C929FF41E677ADA5D3E53CFBA46332'));
assert('rLpq5RcRzA8FU1yUqEPW4xfsdwon7casuM' === Account._publicKeyToAddress('03BFA879C00D58CF55F2B5975FF9B5293008FF49BEFB3EE6BEE2814247BF561A23'));
assert('rP4yWwjoDGF2iZSBdAQAgpC449YDezEbT1' === Account._publicKeyToAddress('02DF0AB18930B6410CA9F55CB37541F1FED891B8EDF8AB1D01D8F23018A4B204A7'));
assert('rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ' === Account._publicKeyToAddress('0310C451A40CAFFD39D6B8A3BD61BF65BCA55246E9DABC3170EBE431D30655B61F'));
});
});
describe('.publicKeyIsActive()', function(){
it('should respond true if the public key corresponds to the account address and the master key IS NOT disabled', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz') {
callback(null, { account_data: {
Account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
Flags: 65536,
LedgerEntryType: 'AccountRoot'
}});
}
}
}, 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz');
account.publicKeyIsActive('025B32A54BFA33FB781581F49B235C0E2820C929FF41E677ADA5D3E53CFBA46332', function(err, is_valid){
assert(err === null);
assert(is_valid === true);
});
});
it('should respond false if the public key corresponds to the account address and the master key IS disabled', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz') {
callback(null, { account_data: {
Account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
Flags: parseInt(65536 | 0x00100000),
LedgerEntryType: 'AccountRoot'
}});
}
}
}, 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz');
account.publicKeyIsActive('025B32A54BFA33FB781581F49B235C0E2820C929FF41E677ADA5D3E53CFBA46332', function(err, is_valid){
assert(err === null);
assert(is_valid === false);
});
});
it('should respond true if the public key corresponds to the regular key', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz') {
callback(null, { account_data: {
Account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
Flags: parseInt(65536 | 0x00100000),
LedgerEntryType: 'AccountRoot',
RegularKey: 'rNw4ozCG514KEjPs5cDrqEcdsi31Jtfm5r'
}});
}
}
}, 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz');
account.publicKeyIsActive('02BE53B7ACBB0900E0BB7729C9CAC1033A0137993B17800BD1191BBD1B29D96A8C', function(err, is_valid){
assert(err === null);
assert(is_valid === true);
});
});
it('should respond false if the public key does not correspond to an active public key for the account', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz') {
callback(null, { account_data: {
Account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
Flags: parseInt(65536 | 0x00100000),
LedgerEntryType: 'AccountRoot',
RegularKey: 'rNw4ozCG514KEjPs5cDrqEcdsi31Jtfm5r'
}});
}
}
}, 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz');
account.publicKeyIsActive('032ECDA93970BC7E8872EF6582CB52A5557F117244A949EB4FA8AC7688CF24FBC8', function(err, is_valid){
assert(err === null);
assert(is_valid === false);
});
});
it('should respond false if the public key is invalid', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz') {
callback(null, { account_data: {
Account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
Flags: parseInt(65536 | 0x00100000),
LedgerEntryType: 'AccountRoot',
RegularKey: 'rNw4ozCG514KEjPs5cDrqEcdsi31Jtfm5r'
}});
}
}
}, 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz');
account.publicKeyIsActive('not a real public key', function(err, is_valid){
assert(err);
});
});
it('should assume the master key is valid for unfunded accounts', function(){
var account = new Account({
on: function(){},
request_account_info: function(address, callback) {
if (address === 'rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ') {
callback({ error: 'remoteError',
error_message: 'Remote reported an error.',
remote:
{ account: 'rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ',
error: 'actNotFound',
error_code: 15,
error_message: 'Account not found.',
id: 3,
ledger_current_index: 6391106,
request:
{ account: 'rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ',
command: 'account_info',
id: 3,
ident: 'rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ' },
status: 'error',
type: 'response' },
result: 'remoteError',
engine_result: 'remoteError',
result_message: 'Remote reported an error.',
engine_result_message: 'Remote reported an error.',
message: 'Remote reported an error.'
});
}
}
}, 'rLdfp6eoR948KVxfn6EpaaNTKwfwXhzSeQ');
account.publicKeyIsActive('0310C451A40CAFFD39D6B8A3BD61BF65BCA55246E9DABC3170EBE431D30655B61F', function(err, is_valid){
assert(!err);
assert(is_valid);
});
});
});
});

View File

@@ -1,373 +1,597 @@
var buster = require("buster");
var assert = require('assert');
var utils = require('./testutils');
var BigInteger = require('../src/js/jsbn/jsbn').BigInteger;
var Amount = utils.load_module('amount').Amount;
var UInt160 = utils.load_module('uint160').UInt160;
var config = utils.get_config();
var jsbn = require('../src/js/ripple/jsbn');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var Amount = require("../src/js/ripple/amount").Amount;
var UInt160 = require("../src/js/ripple/uint160").UInt160;
try {
var conf = require('./config');
} catch(exception) {
var conf = require('./config-example');
}
var config = require('../src/js/ripple/config').load(conf);
// XXX Add test cases that push XRP vs non-XRP behavior.
buster.testCase("Amount", {
"negatives" : {
"Number 1" : function () {
buster.assert.equals("-1", Amount.from_human('0').add(Amount.from_human('-1')).to_human());
},
},
"from_number" : {
"Number 1" : function () {
buster.assert.equals("1/1/rrrrrrrrrrrrrrrrrrrrBZbvji", Amount.from_number(1).to_text_full());
},
},
"UInt160" : {
"Parse 0" : function () {
buster.assert.equals(nbi(), UInt160.from_generic("0")._value);
},
"Parse 0 export" : function () {
buster.assert.equals(UInt160.ACCOUNT_ZERO, UInt160.from_generic("0").to_json());
},
"Parse 1" : function () {
buster.assert.equals(new BigInteger([1]), UInt160.from_generic("1")._value);
},
"Parse rrrrrrrrrrrrrrrrrrrrrhoLvTp export" : function () {
buster.assert.equals(UInt160.ACCOUNT_ZERO, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrrhoLvTp").to_json());
},
"Parse rrrrrrrrrrrrrrrrrrrrBZbvji export" : function () {
buster.assert.equals(UInt160.ACCOUNT_ONE, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrBZbvji").to_json());
},
"Parse mtgox export" : function () {
buster.assert.equals(config.accounts["mtgox"].account, UInt160.from_json("mtgox").to_json());
},
"is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvTp')" : function () {
buster.assert(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvTp"));
},
"!is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvT')" : function () {
buster.refute(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvT"));
},
},
"Amount parsing" : {
"Parse 800/USD/mtgox" : function () {
buster.assert.equals("800/USD/"+config.accounts["mtgox"].account, Amount.from_json("800/USD/mtgox").to_text_full());
},
"Parse native 0" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0").to_text_full());
},
"Parse native 0.0" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0.0").to_text_full());
},
"Parse native -0" : function () {
buster.assert.equals("0/XRP", Amount.from_json("-0").to_text_full());
},
"Parse native -0.0" : function () {
buster.assert.equals("0/XRP", Amount.from_json("-0.0").to_text_full());
},
"Parse native 1000" : function () {
buster.assert.equals("0.001/XRP", Amount.from_json("1000").to_text_full());
},
"Parse native 12.3" : function () {
buster.assert.equals("12.3/XRP", Amount.from_json("12.3").to_text_full());
},
"Parse native -12.3" : function () {
buster.assert.equals("-12.3/XRP", Amount.from_json("-12.3").to_text_full());
},
"Parse 123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
"Parse 12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
"Parse 12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
"Parse 1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("1.23/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
"Parse -0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
"Parse -0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
},
},
"Amount operations" : {
"Negate native 123" : function () {
buster.assert.equals("-0.000123/XRP", Amount.from_json("123").negate().to_text_full());
},
"Negate native -123" : function () {
buster.assert.equals("0.000123/XRP", Amount.from_json("-123").negate().to_text_full());
},
"Negate non-native 123" : function () {
buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
},
"Negate non-native -123" : function () {
buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
},
"Clone non-native -123" : function () {
buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").clone().to_text_full());
},
"Add XRP to XRP" : function () {
buster.assert.equals("0.0002/XRP", Amount.from_json("150").add(Amount.from_json("50")).to_text_full());
},
"Add USD to USD" : function () {
buster.assert.equals("200.52/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("150.02/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").add(Amount.from_json("50.5/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply 0 XRP with 0 XRP" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0").multiply(Amount.from_json("0")).to_text_full());
},
"Multiply 0 USD with 0 XRP" : function () {
buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("0")).to_text_full());
},
"Multiply 0 XRP with 0 USD" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0").multiply(Amount.from_json("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply 1 XRP with 0 XRP" : function () {
buster.assert.equals("0/XRP", Amount.from_json("1").multiply(Amount.from_json("0")).to_text_full());
},
"Multiply 1 USD with 0 XRP" : function () {
buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("0")).to_text_full());
},
"Multiply 1 XRP with 0 USD" : function () {
buster.assert.equals("0/XRP", Amount.from_json("1").multiply(Amount.from_json("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply 0 XRP with 1 XRP" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0").multiply(Amount.from_json("1")).to_text_full());
},
"Multiply 0 USD with 1 XRP" : function () {
buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("1")).to_text_full());
},
"Multiply 0 XRP with 1 USD" : function () {
buster.assert.equals("0/XRP", Amount.from_json("0").multiply(Amount.from_json("1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply XRP with USD" : function () {
buster.assert.equals("2000/XRP", Amount.from_json("200").multiply(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply XRP with USD" : function () {
buster.assert.equals("0.2/XRP", Amount.from_json("20000").multiply(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply XRP with USD" : function () {
buster.assert.equals("20/XRP", Amount.from_json("2000000").multiply(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply XRP with USD, neg" : function () {
buster.assert.equals("-0.002/XRP", Amount.from_json("200").multiply(Amount.from_json("-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply XRP with USD, neg, frac" : function () {
buster.assert.equals("-0.222/XRP", Amount.from_json("-6000").multiply(Amount.from_json("37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply USD with USD" : function () {
buster.assert.equals("0.020000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply USD with USD" : function () {
buster.assert.equals("200000000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply EUR with USD, result < 1" : function () {
buster.assert.equals("100000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply EUR with USD, neg" : function () {
buster.assert.equals("-48000000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply EUR with USD, neg, <1" : function () {
buster.assert.equals("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Multiply EUR with XRP, factor < 1" : function () {
buster.assert.equals("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("2000")).to_text_full());
},
"Multiply EUR with XRP, neg" : function () {
buster.assert.equals("-500/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("5")).to_text_full());
},
"Multiply EUR with XRP, neg, <1" : function () {
buster.assert.equals("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").multiply(Amount.from_json("2000")).to_text_full());
},
"Multiply XRP with XRP" : function () {
buster.assert.equals("0.0001/XRP", Amount.from_json("10").multiply(Amount.from_json("10")).to_text_full());
},
"Divide XRP by USD" : function () {
buster.assert.equals("0.00002/XRP", Amount.from_json("200").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide XRP by USD" : function () {
buster.assert.equals("0.002/XRP", Amount.from_json("20000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide XRP by USD" : function () {
buster.assert.equals("0.2/XRP", Amount.from_json("2000000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide XRP by USD, neg" : function () {
buster.assert.equals("-0.00002/XRP", Amount.from_json("200").divide(Amount.from_json("-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide XRP by USD, neg, frac" : function () {
buster.assert.equals("-0.000162/XRP", Amount.from_json("-6000").divide(Amount.from_json("37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide USD by USD" : function () {
buster.assert.equals("200/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide USD by USD, fractional" : function () {
buster.assert.equals("57142.85714285714/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("35/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide USD by USD" : function () {
buster.assert.equals("20/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide EUR by USD, factor < 1" : function () {
buster.assert.equals("0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide EUR by USD, neg" : function () {
buster.assert.equals("-12/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide EUR by USD, neg, <1" : function () {
buster.assert.equals("-0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
},
"Divide EUR by XRP, result < 1" : function () {
buster.assert.equals("0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
},
"Divide EUR by XRP, neg" : function () {
buster.assert.equals("-20/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("5")).to_text_full());
},
"Divide EUR by XRP, neg, <1" : function () {
buster.assert.equals("-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
}
},
"Amount comparisons" : {
"0 USD == 0 USD" : function () {
var a = Amount.from_json("0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"0 USD == -0 USD" : function () {
var a = Amount.from_json("0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("-0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"0 XRP == 0 XRP" : function () {
var a = Amount.from_json("0");
var b = Amount.from_json("0.0");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"0 XRP == -0 XRP" : function () {
var a = Amount.from_json("0");
var b = Amount.from_json("-0");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"10 USD == 10 USD" : function () {
var a = Amount.from_json("10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"123.4567 USD == 123.4567 USD" : function () {
var a = Amount.from_json("123.4567/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("123.4567/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"10 XRP == 10 XRP" : function () {
var a = Amount.from_json("10");
var b = Amount.from_json("10");
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"1.1 XRP == 1.1 XRP" : function () {
var a = Amount.from_json("1.1");
var b = Amount.from_json("11.0").ratio_human(10);
buster.assert(a.equals(b));
buster.refute(a.not_equals_why(b));
},
"0 USD == 0 USD (ignore issuer)" : function () {
var a = Amount.from_json("0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("0/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP");
buster.assert(a.equals(b, true));
buster.refute(a.not_equals_why(b, true));
},
"1.1 USD == 1.10 USD (ignore issuer)" : function () {
var a = Amount.from_json("1.1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("1.10/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP");
buster.assert(a.equals(b, true));
buster.refute(a.not_equals_why(b, true));
},
describe('Amount', function() {
describe('Negatives', function() {
it('Number 1', function () {
assert.strictEqual(Amount.from_human('0').add(Amount.from_human('-1')).to_human(), '-1');
});
});
describe('Positives', function() {
it('Number 1', function() {
assert(Amount.from_json('1').is_positive());
});
});
describe('from_human', function() {
it('1 XRP', function() {
assert.strictEqual(Amount.from_human("1 XRP").to_text_full(), '1/XRP');
});
it('0.1 XRP', function() {
assert.strictEqual(Amount.from_human("0.1 XRP").to_text_full(), '0.1/XRP');
});
it('0.1 USD', function() {
assert.strictEqual(Amount.from_human("0.1 USD").to_text_full(), '0.1/USD/NaN');
});
});
describe('from_json', function() {
it('1 XRP', function() {
assert.strictEqual(Amount.from_json("1/XRP").to_text_full(), "1/XRP/NaN");
});
});
describe('from_number', function() {
it('Number 1', function() {
assert.strictEqual(Amount.from_number(1).to_text_full(), '1/1/rrrrrrrrrrrrrrrrrrrrBZbvji');
});
it('Number 2', function() {
assert.strictEqual(Amount.from_number(2).to_text_full(), '2/1/rrrrrrrrrrrrrrrrrrrrBZbvji');
});
it('Multiply 2 "1" with 3 "1", by product_human', function () {
assert.strictEqual(Amount.from_number(2).product_human(Amount.from_number(3)).to_text_full(), '6/1/rrrrrrrrrrrrrrrrrrrrBZbvji');
});
it('Multiply 3 USD with 3 "1"', function () {
assert.strictEqual(Amount.from_json('3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_number(3)).to_text_full(), '9/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply -1 "1" with 3 USD', function () {
assert.strictEqual(Amount.from_number(-1).multiply(Amount.from_json('3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full(), '-3/1/rrrrrrrrrrrrrrrrrrrrBZbvji');
});
it('Multiply -1 "1" with 3 USD, by product_human', function () {
assert.strictEqual(Amount.from_number(-1).product_human(Amount.from_json('3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full(), '-3/1/rrrrrrrrrrrrrrrrrrrrBZbvji');
});
});
describe('text_full_rewrite', function() {
it('Number 1', function() {
assert.strictEqual('0.000001/XRP', Amount.text_full_rewrite(1));
});
});
describe('json_rewrite', function() {
it('Number 1', function() {
assert.strictEqual('1', Amount.json_rewrite(1));
});
});
describe('UInt160', function() {
it('Parse 0', function () {
assert.deepEqual(new BigInteger(), UInt160.from_generic('0')._value);
});
it('Parse 0 export', function () {
assert.strictEqual(UInt160.ACCOUNT_ZERO, UInt160.from_generic('0').set_version(0).to_json());
});
it('Parse 1', function () {
assert.deepEqual(new BigInteger([1]), UInt160.from_generic('1')._value);
});
it('Parse rrrrrrrrrrrrrrrrrrrrrhoLvTp export', function () {
assert.strictEqual(UInt160.ACCOUNT_ZERO, UInt160.from_json('rrrrrrrrrrrrrrrrrrrrrhoLvTp').to_json());
});
it('Parse rrrrrrrrrrrrrrrrrrrrBZbvji export', function () {
assert.strictEqual(UInt160.ACCOUNT_ONE, UInt160.from_json('rrrrrrrrrrrrrrrrrrrrBZbvji').to_json());
});
it('Parse mtgox export', function () {
assert.strictEqual(config.accounts['mtgox'].account, UInt160.from_json('mtgox').to_json());
});
it('is_valid rrrrrrrrrrrrrrrrrrrrrhoLvTp', function () {
assert(UInt160.is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvTp'));
});
it('!is_valid rrrrrrrrrrrrrrrrrrrrrhoLvT', function () {
assert(!UInt160.is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvT'));
});
});
describe('Amount validity', function() {
it('is_valid 1', function() {
assert(Amount.is_valid(1));
});
it('is_valid "1"', function() {
assert(Amount.is_valid('1'));
});
it('is_valid "1/XRP"', function() {
assert(Amount.is_valid('1/XRP'));
});
it('!is_valid NaN', function() {
assert(!Amount.is_valid(NaN));
});
it('!is_valid "xx"', function() {
assert(!Amount.is_valid('xx'));
});
it('!is_valid_full 1', function() {
assert(!Amount.is_valid_full(1));
});
it('is_valid_full "1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL"', function() {
assert(Amount.is_valid_full('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL'));
});
});
describe('Amount parsing', function() {
it('Parse invalid string', function() {
assert.strictEqual(Amount.from_json('x').to_text(), '0');
assert.strictEqual(typeof Amount.from_json('x').to_text(true), 'number');
assert(isNaN(Amount.from_json('x').to_text(true)));
});
it('Parse 800/USD/mtgox', function () {
assert.strictEqual('800/USD/'+config.accounts['mtgox'].account, Amount.from_json('800/USD/mtgox').to_text_full());
});
it('Parse native 0', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').to_text_full());
});
it('Parse native 0.0', function () {
assert.strictEqual('0/XRP', Amount.from_json('0.0').to_text_full());
});
it('Parse native -0', function () {
assert.strictEqual('0/XRP', Amount.from_json('-0').to_text_full());
});
it('Parse native -0.0', function () {
assert.strictEqual('0/XRP', Amount.from_json('-0.0').to_text_full());
});
it('Parse native 1000', function () {
assert.strictEqual('0.001/XRP', Amount.from_json('1000').to_text_full());
});
it('Parse native 12.3', function () {
assert.strictEqual('12.3/XRP', Amount.from_json('12.3').to_text_full());
});
it('Parse native -12.3', function () {
assert.strictEqual('-12.3/XRP', Amount.from_json('-12.3').to_text_full());
});
it('Parse 123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse 12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse 12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse 1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('1.23/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse -0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse -0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse 0.0/111/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('0/111/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/111/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
it('Parse 0.0/12D/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
assert.strictEqual('0/XRP/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/12D/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').to_text_full());
});
});
describe('Amount operations', function() {
it('Negate native 123', function () {
assert.strictEqual('-0.000123/XRP', Amount.from_json('123').negate().to_text_full());
});
it('Negate native -123', function () {
assert.strictEqual('0.000123/XRP', Amount.from_json('-123').negate().to_text_full());
});
it('Negate non-native 123', function () {
assert.strictEqual('-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').negate().to_text_full());
});
it('Negate non-native -123', function () {
assert.strictEqual('123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').negate().to_text_full());
});
it('Clone non-native -123', function () {
assert.strictEqual('-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').clone().to_text_full());
});
it('Add XRP to XRP', function () {
assert.strictEqual('0.0002/XRP', Amount.from_json('150').add(Amount.from_json('50')).to_text_full());
});
it('Add USD to USD', function () {
assert.strictEqual('200.52/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('150.02/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').add(Amount.from_json('50.5/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Add 0 USD to 1 USD', function() {
assert.strictEqual('1' , Amount.from_json('1/USD').add('0/USD').to_text());
});
it('Subtract USD from USD', function() {
assert.strictEqual('99.52/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('150.02/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').subtract(Amount.from_json('50.5/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply 0 XRP with 0 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').multiply(Amount.from_json('0')).to_text_full());
});
it('Multiply 0 USD with 0 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('0')).to_text_full());
});
it('Multiply 0 XRP with 0 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').multiply(Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply 1 XRP with 0 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('1').multiply(Amount.from_json('0')).to_text_full());
});
it('Multiply 1 USD with 0 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('0')).to_text_full());
});
it('Multiply 1 XRP with 0 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('1').multiply(Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply 0 XRP with 1 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').multiply(Amount.from_json('1')).to_text_full());
});
it('Multiply 0 USD with 1 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('1')).to_text_full());
});
it('Multiply 0 XRP with 1 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').multiply(Amount.from_json('1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.equal('0.002/XRP', Amount.from_json('200').multiply(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.strictEqual('0.2/XRP', Amount.from_json('20000').multiply(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.strictEqual('20/XRP', Amount.from_json('2000000').multiply(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD, neg', function () {
assert.strictEqual('-0.002/XRP', Amount.from_json('200').multiply(Amount.from_json('-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD, neg, frac', function () {
assert.strictEqual('-0.222/XRP', Amount.from_json('-6000').multiply(Amount.from_json('37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply USD with USD', function () {
assert.strictEqual('20000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply USD with USD', function () {
assert.strictEqual('200000000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with USD, result < 1', function () {
assert.strictEqual('100000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with USD, neg', function () {
assert.strictEqual('-48000000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with USD, neg, <1', function () {
assert.strictEqual('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with XRP, factor < 1', function () {
assert.strictEqual('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('2000')).to_text_full());
});
it('Multiply EUR with XRP, neg', function () {
assert.strictEqual('-500/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('5')).to_text_full());
});
it('Multiply EUR with XRP, neg, <1', function () {
assert.strictEqual('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').multiply(Amount.from_json('2000')).to_text_full());
});
it('Multiply XRP with XRP', function () {
assert.strictEqual('0.0001/XRP', Amount.from_json('10').multiply(Amount.from_json('10')).to_text_full());
});
it('Divide XRP by USD', function () {
assert.strictEqual('0.00002/XRP', Amount.from_json('200').divide(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide XRP by USD', function () {
assert.strictEqual('0.002/XRP', Amount.from_json('20000').divide(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide XRP by USD', function () {
assert.strictEqual('0.2/XRP', Amount.from_json('2000000').divide(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide XRP by USD, neg', function () {
assert.strictEqual('-0.00002/XRP', Amount.from_json('200').divide(Amount.from_json('-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide XRP by USD, neg, frac', function () {
assert.strictEqual('-0.000162/XRP', Amount.from_json('-6000').divide(Amount.from_json('37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide USD by USD', function () {
assert.strictEqual('200/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide USD by USD, fractional', function () {
assert.strictEqual('57142.85714285714/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('35/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide USD by USD', function () {
assert.strictEqual('20/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide EUR by USD, factor < 1', function () {
assert.strictEqual('0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide EUR by USD, neg', function () {
assert.strictEqual('-12/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide EUR by USD, neg, <1', function () {
assert.strictEqual('-0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Divide EUR by XRP, result < 1', function () {
assert.strictEqual('0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('2000')).to_text_full());
});
it('Divide EUR by XRP, neg', function () {
assert.strictEqual('-20/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('5')).to_text_full());
});
it('Divide EUR by XRP, neg, <1', function () {
assert.strictEqual('-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').divide(Amount.from_json('2000')).to_text_full());
});
it('Divide by zero should throw', function() {
assert.throws(function() {
Amount.from_json(1).divide(Amount.from_json(0));
});
});
it('Divide zero by number', function() {
assert.strictEqual('0', Amount.from_json(0).divide(Amount.from_json(1)).to_text());
});
it('Divide invalid by number', function() {
assert.throws(function() {
Amount.from_json('x').divide(Amount.from_json('1'));
});
});
it('Divide number by invalid', function() {
assert.throws(function() {
Amount.from_json('1').divide(Amount.from_json('x'));
});
});
it('amount.abs -1 == 1', function() {
assert.strictEqual('1', Amount.from_json(-1).abs().to_text());
});
it('amount.copyTo native', function() {
assert(isNaN(Amount.from_json('x').copyTo(new Amount())._value));
});
it('amount.copyTo zero', function() {
assert(!(Amount.from_json(0).copyTo(new Amount())._is_negative))
});
});
describe('Amount comparisons', function() {
it('0 USD == 0 USD amount.equals string argument', function() {
var a = '0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL';
assert(Amount.from_json(a).equals(a));
});
it('0 USD == 0 USD', function () {
var a = Amount.from_json('0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('0 USD == -0 USD', function () {
var a = Amount.from_json('0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('-0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('0 XRP == 0 XRP', function () {
var a = Amount.from_json('0');
var b = Amount.from_json('0.0');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('0 XRP == -0 XRP', function () {
var a = Amount.from_json('0');
var b = Amount.from_json('-0');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('10 USD == 10 USD', function () {
var a = Amount.from_json('10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('123.4567 USD == 123.4567 USD', function () {
var a = Amount.from_json('123.4567/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('123.4567/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('10 XRP == 10 XRP', function () {
var a = Amount.from_json('10');
var b = Amount.from_json('10');
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('1.1 XRP == 1.1 XRP', function () {
var a = Amount.from_json('1.1');
var b = Amount.from_json('11.0').ratio_human(10);
assert(a.equals(b));
assert(!a.not_equals_why(b));
});
it('0 USD == 0 USD (ignore issuer)', function () {
var a = Amount.from_json('0/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('0/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP');
assert(a.equals(b, true));
assert(!a.not_equals_why(b, true));
});
it('1.1 USD == 1.10 USD (ignore issuer)', function () {
var a = Amount.from_json('1.1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('1.10/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP');
assert(a.equals(b, true));
assert(!a.not_equals_why(b, true));
});
// Exponent mismatch
"10 USD != 100 USD" : function () {
var a = Amount.from_json("10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("100/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP value differs.");
},
"10 XRP != 100 XRP" : function () {
var a = Amount.from_json("10");
var b = Amount.from_json("100");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "XRP value differs.");
},
it('10 USD != 100 USD', function () {
var a = Amount.from_json('10/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('100/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP value differs.');
});
it('10 XRP != 100 XRP', function () {
var a = Amount.from_json('10');
var b = Amount.from_json('100');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'XRP value differs.');
});
// Mantissa mismatch
"1 USD != 2 USD" : function () {
var a = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("2/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP value differs.");
},
"1 XRP != 2 XRP" : function () {
var a = Amount.from_json("1");
var b = Amount.from_json("2");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "XRP value differs.");
},
"0.1 USD != 0.2 USD" : function () {
var a = Amount.from_json("0.1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("0.2/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP value differs.");
},
it('1 USD != 2 USD', function () {
var a = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('2/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP value differs.');
});
it('1 XRP != 2 XRP', function () {
var a = Amount.from_json('1');
var b = Amount.from_json('2');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'XRP value differs.');
});
it('0.1 USD != 0.2 USD', function () {
var a = Amount.from_json('0.1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('0.2/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP value differs.');
});
// Sign mismatch
"1 USD != -1 USD" : function () {
var a = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("-1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP sign differs.");
},
"1 XRP != -1 XRP" : function () {
var a = Amount.from_json("1");
var b = Amount.from_json("-1");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "XRP sign differs.");
},
"1 USD != 1 USD (issuer mismatch)" : function () {
var a = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("1/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP issuer differs: rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
},
"1 USD != 1 EUR" : function () {
var a = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("1/EUR/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Non-XRP currency differs.");
},
"1 USD != 1 XRP" : function () {
var a = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
var b = Amount.from_json("1");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Native mismatch.");
},
"1 XRP != 1 USD" : function () {
var a = Amount.from_json("1");
var b = Amount.from_json("1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL");
buster.refute(a.equals(b));
buster.assert.equals(a.not_equals_why(b), "Native mismatch.");
}
}
});
it('1 USD != -1 USD', function () {
var a = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('-1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP sign differs.');
});
it('1 XRP != -1 XRP', function () {
var a = Amount.from_json('1');
var b = Amount.from_json('-1');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'XRP sign differs.');
});
it('1 USD != 1 USD (issuer mismatch)', function () {
var a = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('1/USD/rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP issuer differs: rH5aWQJ4R7v4Mpyf4kDBUvDFT5cbpFq3XP/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
});
it('1 USD != 1 EUR', function () {
var a = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('1/EUR/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Non-XRP currency differs.');
});
it('1 USD != 1 XRP', function () {
var a = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
var b = Amount.from_json('1');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Native mismatch.');
});
it('1 XRP != 1 USD', function () {
var a = Amount.from_json('1');
var b = Amount.from_json('1/USD/rNDKeo9RrCiRdfsMG8AdoZvNZxHASGzbZL');
assert(!a.equals(b));
assert.strictEqual(a.not_equals_why(b), 'Native mismatch.');
});
});
// vim:sw=2:sts=2:ts=8:et
describe('product_human', function() {
it('Multiply 0 XRP with 0 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').product_human(Amount.from_json('0')).to_text_full());
});
it('Multiply 0 USD with 0 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('0')).to_text_full());
});
it('Multiply 0 XRP with 0 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').product_human(Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply 1 XRP with 0 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('1').product_human(Amount.from_json('0')).to_text_full());
});
it('Multiply 1 USD with 0 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('0')).to_text_full());
});
it('Multiply 1 XRP with 0 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('1').product_human(Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply 0 XRP with 1 XRP', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').product_human(Amount.from_json('1')).to_text_full());
});
it('Multiply 0 USD with 1 XRP', function () {
assert.strictEqual('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('1')).to_text_full());
});
it('Multiply 0 XRP with 1 USD', function () {
assert.strictEqual('0/XRP', Amount.from_json('0').product_human(Amount.from_json('1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.equal('0.002/XRP', Amount.from_json('200').product_human(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.strictEqual('0.2/XRP', Amount.from_json('20000').product_human(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD', function () {
assert.strictEqual('20/XRP', Amount.from_json('2000000').product_human(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD, neg', function () {
assert.strictEqual('-0.002/XRP', Amount.from_json('200').product_human(Amount.from_json('-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply XRP with USD, neg, frac', function () {
assert.strictEqual('-0.222/XRP', Amount.from_json('-6000').product_human(Amount.from_json('37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply USD with USD', function () {
assert.strictEqual('20000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply USD with USD', function () {
assert.strictEqual('200000000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with USD, result < 1', function () {
assert.strictEqual('100000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', Amount.from_json('100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full());
});
it('Multiply EUR with USD, neg', function () {
assert.strictEqual(Amount.from_json('-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full(), '-48000000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply EUR with USD, neg, <1', function () {
assert.strictEqual(Amount.from_json('0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh')).to_text_full(), '-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply EUR with XRP, factor < 1', function () {
assert.strictEqual(Amount.from_json('0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('2000')).to_text_full(), '0.0001/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply EUR with XRP, neg', function () {
assert.strictEqual(Amount.from_json('-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('5')).to_text_full(), '-0.0005/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply EUR with XRP, neg, <1', function () {
assert.strictEqual(Amount.from_json('-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('2000')).to_text_full(), '-0.0001/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Multiply XRP with XRP', function () {
assert.strictEqual(Amount.from_json('10000000').product_human(Amount.from_json('10')).to_text_full(), '0.0001/XRP');
});
it('Multiply USD with XAU (dem)', function () {
assert.strictEqual(Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').product_human(Amount.from_json('10/015841551A748AD2C1F76FF6ECB0CCCD00000000/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'), {reference_date: 443845330 + 31535000}).to_text_full(), '19900.00316303882/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
});
describe('ratio_human', function() {
it('Divide USD by XAU (dem)', function () {
assert.strictEqual(Amount.from_json('2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').ratio_human(Amount.from_json('10/015841551A748AD2C1F76FF6ECB0CCCD00000000/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'), {reference_date: 443845330 + 31535000}).to_text_full(), '201.0049931765529/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
});
describe('_invert', function() {
it('Invert 1', function () {
assert.strictEqual(Amount.from_json('1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').invert().to_text_full(), '1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Invert 20', function () {
assert.strictEqual(Amount.from_json('20/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').invert().to_text_full(), '0.05/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Invert 0.02', function () {
assert.strictEqual(Amount.from_json('0.02/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh').invert().to_text_full(), '50/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
});
describe('from_quality', function() {
it('BTC/XRP', function () {
assert.strictEqual(Amount.from_quality('7B73A610A009249B0CC0D4311E8BA7927B5A34D86634581C5F0FF9FF678E1000', 'XRP', NaN, {base_currency: 'BTC'}).to_text_full(), '44,970/XRP');
});
it('BTC/XRP inverse', function () {
assert.strictEqual(Amount.from_quality('37AAC93D336021AE94310D0430FFA090F7137C97D473488C4A0918D0DEF8624E', 'XRP', NaN, {inverse: true, base_currency: 'BTC'}).to_text_full(), '39,053.954453/XRP');
});
it('XRP/USD', function () {
assert.strictEqual(Amount.from_quality('DFA3B6DDAB58C7E8E5D944E736DA4B7046C30E4F460FD9DE4D05DCAA8FE12000', 'USD', 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', {base_currency: 'XRP'}).to_text_full(), '0.0165/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
});
it('XRP/USD inverse', function () {
assert.strictEqual(Amount.from_quality('4627DFFCFF8B5A265EDBD8AE8C14A52325DBFEDAF4F5C32E5C22A840E27DCA9B', 'USD', 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', {inverse: true, base_currency: 'XRP'}).to_text_full(), '0.010251/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
});
it('BTC/USD', function () {
assert.strictEqual(Amount.from_quality('6EAB7C172DEFA430DBFAD120FDC373B5F5AF8B191649EC9858038D7EA4C68000', 'USD', 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', {base_currency: 'BTC'}).to_text_full(), '1000/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
});
it('BTC/USD inverse', function () {
assert.strictEqual(Amount.from_quality('20294C923E80A51B487EB9547B3835FD483748B170D2D0A455071AFD498D0000', 'USD', 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', {inverse: true, base_currency: 'BTC'}).to_text_full(), '0.5/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
});
it('XAU(dem)/XRP', function () {
assert.strictEqual(Amount.from_quality('587322CCBDE0ABD01704769A73A077C32FB39057D813D4165F1FF973CAF997EF', 'XRP', NaN, {base_currency: '015841551A748AD2C1F76FF6ECB0CCCD00000000', reference_date: 443845330 + 31535000}).to_text_full(), '90,452.246928/XRP');
});
it('XAU(dem)/XRP inverse', function () {
assert.strictEqual(Amount.from_quality('F72C7A9EAE4A45ED1FB547AD037D07B9B965C6E662BEBAFA4A03F2A976804235', 'XRP', NaN, {inverse: true, base_currency: '015841551A748AD2C1F76FF6ECB0CCCD00000000', reference_date: 443845330 + 31535000}).to_text_full(), '90,442.196677/XRP');
});
it('USD/XAU(dem)', function () {
assert.strictEqual(Amount.from_quality('4743E58E44974B325D42FD2BB683A6E36950F350EE46DD3A521B644B99782F5F', '015841551A748AD2C1F76FF6ECB0CCCD00000000', 'rUyPiNcSFFj6uMR2gEaD8jUerQ59G1qvwN', {base_currency: 'USD', reference_date: 443845330 + 31535000}).to_text_full(), '0.007710100231303007/XAU (-0.5%pa)/rUyPiNcSFFj6uMR2gEaD8jUerQ59G1qvwN');
});
it('USD/XAU(dem) inverse', function () {
assert.strictEqual(Amount.from_quality('CDFD3AFB2F8C5DBEF75B081F7C957FF5509563266F28F36C5704A0FB0BAD8800', '015841551A748AD2C1F76FF6ECB0CCCD00000000', 'rUyPiNcSFFj6uMR2gEaD8jUerQ59G1qvwN', {inverse: true, base_currency: 'USD', reference_date: 443845330 + 31535000}).to_text_full(), '0.007675186123263489/XAU (-0.5%pa)/rUyPiNcSFFj6uMR2gEaD8jUerQ59G1qvwN');
});
});
});

View File

@@ -1,26 +1,19 @@
var buster = require("buster");
var assert = require('assert');
var utils = require('./testutils');
var Seed = utils.load_module('seed').Seed;
var config = require('./testutils').get_config();
var Seed = require("../src/js/ripple/seed").Seed;
try {
var conf = require('./config');
} catch(exception) {
var conf = require('./config-example');
}
var config = require('../src/js/ripple/config').load(conf);
buster.testCase("Base58", {
"Seed" : {
"saESc82Vun7Ta5EJRzGJbrXb5HNYk" : function () {
var seed = Seed.from_json("saESc82Vun7Ta5EJRzGJbrXb5HNYk");
buster.assert.equals(seed.to_hex(), "FF1CF838D02B2CF7B45BAC27F5F24F4F");
},
"sp6iDHnmiPN7tQFHm5sCW59ax3hfE" : function () {
var seed = Seed.from_json("sp6iDHnmiPN7tQFHm5sCW59ax3hfE");
buster.assert.equals(seed.to_hex(), "00AD8DA764C3C8AF5F9B8D51C94B9E49");
}
}
describe('Base58', function() {
describe('Seed', function() {
it('saESc82Vun7Ta5EJRzGJbrXb5HNYk', function () {
var seed = Seed.from_json('saESc82Vun7Ta5EJRzGJbrXb5HNYk');
assert.strictEqual(seed.to_hex(), 'FF1CF838D02B2CF7B45BAC27F5F24F4F');
});
it('sp6iDHnmiPN7tQFHm5sCW59ax3hfE', function () {
var seed = Seed.from_json('sp6iDHnmiPN7tQFHm5sCW59ax3hfE');
assert.strictEqual(seed.to_hex(), '00AD8DA764C3C8AF5F9B8D51C94B9E49');
});
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,11 +0,0 @@
var config = module.exports;
config["ripple-lib"] = {
rootPath: "../",
environment: "node",
tests: [
"test/*-test.js"
]
}
// vim:sw=2:sts=2:ts=8:et

186
test/currency-test.js Normal file
View File

@@ -0,0 +1,186 @@
var assert = require('assert');
var utils = require('./testutils');
var currency = utils.load_module('currency').Currency;
describe('Currency', function() {
describe('json_rewrite', function() {
it('json_rewrite("USD") == "USD"', function() {
assert.strictEqual('USD', currency.json_rewrite('USD'));
});
it('json_rewrite("NaN") == "XRP"', function() {
assert.strictEqual('XRP', currency.json_rewrite(NaN));
});
it('json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000") == "XAU (-0.5%pa)"', function() {
assert.strictEqual(currency.json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000"),
"XAU (-0.5%pa)");
});
});
describe('from_json', function() {
it('from_json(NaN).to_json() == "XRP"', function() {
var r = currency.from_json(NaN);
assert(!r.is_valid());
assert.strictEqual('XRP', r.to_json());
});
it('from_json("XRP").to_json() == "XRP"', function() {
var r = currency.from_json('XRP');
assert(r.is_valid());
assert(r.is_native());
assert.strictEqual('XRP', r.to_json());
});
it('from_json("111").to_human()', function() {
var r = currency.from_json("111");
assert(r.is_valid());
assert.strictEqual('111', r.to_json());
});
it('from_json("1D2").to_human()', function() {
var r = currency.from_json("1D2");
assert(!r.is_valid());
assert.strictEqual('XRP', r.to_json());
});
});
describe('from_human', function() {
it('From human "USD - Gold (-25%pa)"', function() {
var cur = currency.from_human('USD - Gold (-25%pa)');
assert.strictEqual(cur.to_json(), 'USD (-25%pa)');
assert.strictEqual(cur.to_hex(), '0155534400000000C19A22BC51297F0B00000000');
assert.strictEqual(cur.to_json(), cur.to_human());
});
it('From human "EUR (-0.5%pa)', function() {
var cur = currency.from_human('EUR (-0.5%pa)');
assert.strictEqual(cur.to_json(), 'EUR (-0.5%pa)');
});
it('From human "EUR (0.5361%pa)", test decimals', function() {
var cur = currency.from_human('EUR (0.5361%pa)');
assert.strictEqual(cur.to_json(), 'EUR (0.54%pa)');
assert.strictEqual(cur.to_json({decimals:4}), 'EUR (0.5361%pa)');
assert.strictEqual(cur.get_interest_percentage_at(undefined, 4), 0.5361);
});
it('From human "EUR - Euro (0.5361%pa)", test decimals and full_name', function() {
var cur = currency.from_human('EUR (0.5361%pa)');
assert.strictEqual(cur.to_json(), 'EUR (0.54%pa)');
assert.strictEqual(cur.to_json({decimals:4, full_name:'Euro'}), 'EUR - Euro (0.5361%pa)');
assert.strictEqual(cur.get_interest_percentage_at(undefined, 4), 0.5361);
});
it('From human "TYX - 30-Year Treasuries (1.5%pa)"', function() {
var cur = currency.from_human('TYX - 30-Year Treasuries (1.5%pa)');
assert.strictEqual(cur.to_json(), 'TYX (1.5%pa)');
});
it('From human "TYX - 30-Year Treasuries"', function() {
var cur = currency.from_human('TYX - 30-Year Treasuries');
assert.strictEqual(cur.to_json(), 'TYX');
});
it('From human "INR - Indian Rupees (-0.5%)"', function() {
var cur = currency.from_human('INR - Indian Rupees (-0.5%pa)');
assert.strictEqual(cur.to_json(), 'INR (-0.5%pa)');
});
it('From human "INR - 30 Indian Rupees"', function() {
var cur = currency.from_human('INR - 30 Indian Rupees');
assert.strictEqual(cur.to_json(), 'INR');
});
});
describe('to_human', function() {
it('"USD".to_human() == "USD"', function() {
assert.strictEqual('USD', currency.from_json('USD').to_human());
});
it('"NaN".to_human() == "XRP"', function() {
assert.strictEqual('XRP', currency.from_json(NaN).to_human());
});
it('"015841551A748AD2C1F76FF6ECB0CCCD00000000") == "015841551A748AD2C1F76FF6ECB0CCCD00000000"', function() {
assert.strictEqual(currency.from_json("015841551A748AD2C1F76FF6ECB0CCCD00000000").to_human(),
'XAU (-0.5%pa)');
});
it('to_human with full_name "USD - US Dollar"', function() {
assert.strictEqual('USD - US Dollar', currency.from_json('USD').to_human({full_name:'US Dollar'}));
});
it('to_human with full_name "XRP - Ripples"', function() {
assert.strictEqual('XRP - Ripples', currency.from_json('XRP').to_human({full_name:'Ripples'}));
});
});
describe('from_hex', function() {
it('"015841551A748AD2C1F76FF6ECB0CCCD00000000" === "XAU (-0.5%pa)"', function() {
var cur = currency.from_hex('015841551A748AD2C1F76FF6ECB0CCCD00000000');
assert.strictEqual(cur.to_json(), 'XAU (-0.5%pa)');
assert.strictEqual(cur.to_hex(), '015841551A748AD2C1F76FF6ECB0CCCD00000000');
assert.strictEqual(cur.to_json(), cur.to_human());
});
});
describe('parse_json(currency obj)', function() {
assert.strictEqual('USD', new currency().parse_json(currency.from_json('USD')).to_json());
assert.strictEqual('USD (0.5%pa)', new currency().parse_json(currency.from_json('USD (0.5%pa)')).to_json());
});
describe('is_valid', function() {
it('Currency.is_valid("XRP")', function() {
assert(currency.is_valid('XRP'));
});
it('!Currency.is_valid(NaN)', function() {
assert(!currency.is_valid(NaN));
});
it('from_json("XRP").is_valid()', function() {
assert(currency.from_json('XRP').is_valid());
});
it('!from_json(NaN).is_valid()', function() {
assert(!currency.from_json(NaN).is_valid());
});
});
describe('clone', function() {
it('should clone currency object', function() {
var c = currency.from_json('XRP');
assert.strictEqual('XRP', c.clone().to_json());
});
});
describe('to_human', function() {
it('should generate human string', function() {
assert.strictEqual('XRP', currency.from_json('XRP').to_human());
});
});
describe('has_interest', function() {
it('should be true for type 1 currency codes', function() {
assert(currency.from_hex('015841551A748AD2C1F76FF6ECB0CCCD00000000').has_interest());
assert(currency.from_json('015841551A748AD2C1F76FF6ECB0CCCD00000000').has_interest());
});
it('should be false for type 0 currency codes', function() {
assert(!currency.from_hex('0000000000000000000000005553440000000000').has_interest());
assert(!currency.from_json('USD').has_interest());
});
});
function precision(num, precision) {
return +(Math.round(num + "e+"+precision) + "e-"+precision);
}
describe('get_interest_at', function() {
it('returns demurred value for demurrage currency', function() {
var cur = currency.from_json('015841551A748AD2C1F76FF6ECB0CCCD00000000');
// At start, no demurrage should occur
assert.equal(1, cur.get_interest_at(443845330));
// After one year, 0.5% should have occurred
assert.equal(0.995, precision(cur.get_interest_at(443845330 + 31536000), 14));
// After one demurrage period, 1/e should have occurred
assert.equal(1/Math.E, cur.get_interest_at(443845330 + 6291418827.05));
// One year before start, it should be (roughly) 0.5% higher.
assert.equal(1.005, precision(cur.get_interest_at(443845330 - 31536000), 4));
// One demurrage period before start, rate should be e
assert.equal(Math.E, cur.get_interest_at(443845330 - 6291418827.05));
});
});
describe('get_iso', function() {
it('should get "XRP" iso_code', function() {
assert.strictEqual('XRP', currency.from_json('XRP').get_iso());
});
it('should get iso_code', function() {
assert.strictEqual('USD', currency.from_json('USD - US Dollar').get_iso());
});
it('should get iso_code', function() {
assert.strictEqual('USD', currency.from_json('USD (0.5%pa)').get_iso());
});
});
});

1
test/fixtures/ledger-full-38129.json vendored Normal file

File diff suppressed because one or more lines are too long

1
test/fixtures/ledger-full-40000.json vendored Normal file

File diff suppressed because one or more lines are too long

14
test/keypair-test.js Normal file
View File

@@ -0,0 +1,14 @@
var assert = require('assert');
var utils = require('./testutils');
var Seed = utils.load_module('seed').Seed;
var config = require('./testutils').get_config();
describe('KeyPair', function() {
it('can generate an address', function () {
var seed = Seed.from_json("masterpassphrase");
var address = seed.get_key().get_address();
assert.strictEqual(address.to_json(), 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
});
// vim:sw=2:sts=2:ts=8:et

88
test/ledger-test.js Normal file
View File

@@ -0,0 +1,88 @@
var assert = require('assert');
var fs = require('fs');
var utils = require('./testutils');
var Ledger = utils.load_module('ledger').Ledger;
var config = require('./testutils').get_config();
/**
* @param ledger_index {Number}
* Expects a corresponding ledger dump in $repo/test/fixtures/ folder
*/
create_ledger_test = function (ledger_index) {
describe(String(ledger_index), function() {
var path = __dirname + '/fixtures/ledger-full-'+ledger_index+'.json';
var ledger_raw = fs.readFileSync(path),
ledger_json = JSON.parse(ledger_raw),
ledger = Ledger.from_json(ledger_json);
it('has account_hash of '+ ledger_json.account_hash, function() {
assert.equal(ledger_json.account_hash,
ledger.calc_account_hash({sanity_test:true}).to_hex());
})
it('has transaction_hash of '+ ledger_json.transaction_hash, function() {
assert.equal(ledger_json.transaction_hash,
ledger.calc_tx_hash().to_hex());
})
})
}
describe('Ledger', function() {
// This is the first recorded ledger with a non empty transaction set
create_ledger_test(38129);
// Because, why not.
create_ledger_test(40000);
describe('#calcAccountRootEntryHash', function () {
it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh';
var expectedEntryHash = '2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8';
var actualEntryHash = Ledger.calcAccountRootEntryHash(account);
assert.equal(actualEntryHash.to_hex(), expectedEntryHash);
});
});
describe('#calcRippleStateEntryHash', function () {
it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function () {
var account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh';
var account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY';
var currency = 'USD';
var expectedEntryHash = 'C683B5BB928F025F1E860D9D69D6C554C2202DE0D45877ADB3077DA4CB9E125C';
var actualEntryHash1 = Ledger.calcRippleStateEntryHash(account1, account2, currency);
var actualEntryHash2 = Ledger.calcRippleStateEntryHash(account2, account1, currency);
assert.equal(actualEntryHash1.to_hex(), expectedEntryHash);
assert.equal(actualEntryHash2.to_hex(), expectedEntryHash);
});
it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function () {
var account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV';
var account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj';
var currency = 'UAM';
var expectedEntryHash = 'AE9ADDC584358E5847ADFC971834E471436FC3E9DE6EA1773DF49F419DC0F65E';
var actualEntryHash1 = Ledger.calcRippleStateEntryHash(account1, account2, currency);
var actualEntryHash2 = Ledger.calcRippleStateEntryHash(account2, account1, currency);
assert.equal(actualEntryHash1.to_hex(), expectedEntryHash);
assert.equal(actualEntryHash2.to_hex(), expectedEntryHash);
});
});
describe('#calcOfferEntryHash', function () {
it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function () {
var account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw';
var sequence = 137
var expectedEntryHash = '03F0AED09DEEE74CEF85CD57A0429D6113507CF759C597BABB4ADB752F734CE3';
var actualEntryHash = Ledger.calcOfferEntryHash(account, sequence);
assert.equal(actualEntryHash.to_hex(), expectedEntryHash);
});
});
});
// vim:sw=2:sts=2:ts=8:et

325
test/message-test.js Normal file
View File

@@ -0,0 +1,325 @@
var assert = require('assert');
var sjcl = require('../build/sjcl');
var Message = require('../src/js/ripple/message').Message;
var Seed = require('../src/js/ripple/seed').Seed;
var Remote = require('../src/js/ripple/remote').Remote;
describe('Message', function(){
describe('signMessage', function(){
it('should prepend the MAGIC_BYTES, call the HASH_FUNCTION, and then call signHash', function(){
var normal_signHash = Message.signHash;
var message_text = 'Hello World!';
var signHash_called = false;
Message.signHash = function(hash) {
signHash_called = true;
assert.deepEqual(hash, Message.HASH_FUNCTION(Message.MAGIC_BYTES + message_text));
};
Message.signMessage(message_text);
assert(signHash_called);
Message.signHash = normal_signHash;
});
});
describe('signHash', function(){
it('should accept the hash as either a hex string or a bitArray', function(){
var normal_random = sjcl.random.randomWords;
sjcl.random.randomWords = function(num_words){
var words = [];
for (var w = 0; w < num_words; w++) {
words.push(sjcl.codec.hex.toBits('00000000'));
}
return words;
};
var secret_string = 'safRpB5euNL52PZPTSqrE9gvuFwTC';
// var address = 'rLLzaq61D633b5hhbNXKM9CkrYHboobVv3';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
var signature1 = Message.signHash(hash, secret_string);
var signature2 = Message.signHash(sjcl.codec.hex.toBits(hash), secret_string);
assert.strictEqual(signature1, signature2);
sjcl.random.randomWords = normal_random;
});
it('should accept the secret as a string or scjl.ecc.ecdsa.secretKey object', function(){
var normal_random = sjcl.random.randomWords;
sjcl.random.randomWords = function(num_words){
var words = [];
for (var w = 0; w < num_words; w++) {
words.push(sjcl.codec.hex.toBits('00000000'));
}
return words;
};
var secret_string = 'safRpB5euNL52PZPTSqrE9gvuFwTC';
// var address = 'rLLzaq61D633b5hhbNXKM9CkrYHboobVv3';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
var signature1 = Message.signHash(hash, secret_string);
var signature2 = Message.signHash(hash, Seed.from_json(secret_string).get_key()._secret);
assert.strictEqual(signature1, signature2);
sjcl.random.randomWords = normal_random;
});
it('should throw an error if given an invalid secret key', function(){
var secret_string = 'badsafRpB5euNL52PZPTSqrE9gvuFwTC';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
assert.throws(function(){
Message.signHash(hash, secret_string);
}, /Cannot\ generate\ keys\ from\ invalid\ seed/);
});
it('should throw an error if the parameters are reversed', function(){
var secret_string = 'safRpB5euNL52PZPTSqrE9gvuFwTC';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
assert.throws(function(){
Message.signHash(secret_string, hash);
}, Error);
assert.throws(function(){
Message.signHash(secret_string, sjcl.codec.hex.toBits(hash));
}, Error);
assert.throws(function(){
Message.signHash(Seed.from_json(secret_string).get_key()._secret, hash);
}, Error);
assert.throws(function(){
Message.signHash(Seed.from_json(secret_string).get_key()._secret, sjcl.codec.hex.toBits(hash));
}, Error);
});
it('should produce a base64-encoded signature', function(){
var REGEX_BASE64 = /^([A-Za-z0-9\+]{4})*([A-Za-z0-9\+]{2}==)|([A-Za-z0-9\+]{3}=)?$/;
var normal_random = sjcl.random.randomWords;
sjcl.random.randomWords = function(num_words){
var words = [];
for (var w = 0; w < num_words; w++) {
words.push(sjcl.codec.hex.toBits('00000000'));
}
return words;
};
var secret_string = 'safRpB5euNL52PZPTSqrE9gvuFwTC';
// var address = 'rLLzaq61D633b5hhbNXKM9CkrYHboobVv3';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
var signature = Message.signHash(hash, secret_string);
assert(REGEX_BASE64.test(signature));
sjcl.random.randomWords = normal_random;
});
});
describe('verifyMessageSignature', function(){
it('should prepend the MAGIC_BYTES, call the HASH_FUNCTION, and then call verifyHashSignature', function(){
var normal_verifyHashSignature = Message.verifyHashSignature;
var data = {
message: 'Hello world!',
signature: 'AAAAGzFa1pYjhssCpDFZgFSnYQ8qCnMkLaZrg0mXZyNQ2NxgMQ8z9U3ngYerxSZCEt3Q4raMIpt03db7jDNGbfmHy8I='
};
var verifyHashSignature_called = false;
Message.verifyHashSignature = function(vhs_data, remote, callback) {
verifyHashSignature_called = true;
assert.deepEqual(vhs_data.hash, Message.HASH_FUNCTION(Message.MAGIC_BYTES + data.message));
assert.strictEqual(vhs_data.signature, data.signature);
callback();
};
Message.verifyMessageSignature(data, {}, function(err){
assert(!err);
});
assert(verifyHashSignature_called);
Message.verifyHashSignature = normal_verifyHashSignature;
});
});
describe('verifyHashSignature', function(){
it('should throw an error if a callback function is not supplied', function(){
var data = {
message: 'Hello world!',
hash: '861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8',
signature: 'AAAAHOUJQzG/7BO82fGNt1TNE+GGVXKuQQ0N2nTO+iJETE69PiHnaAkkOzovM177OosxbKjpt3KvwuJflgUB2YGvgjk=',
account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz'
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
assert.throws(function(){
Message.verifyHashSignature(data);
}, /(?=.*callback\ function).*/);
});
it('should respond with an error if the hash is missing or invalid', function(done){
var data = {
message: 'Hello world!',
signature: 'AAAAHOUJQzG/7BO82fGNt1TNE+GGVXKuQQ0N2nTO+iJETE69PiHnaAkkOzovM177OosxbKjpt3KvwuJflgUB2YGvgjk=',
account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz'
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
test_remote.state = 'online';
Message.verifyHashSignature(data, test_remote, function(err, valid){
assert(/hash/i.test(err.message));
done();
});
});
it('should respond with an error if the account is missing or invalid', function(done){
var data = {
message: 'Hello world!',
hash: '861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8',
signature: 'AAAAHOUJQzG/7BO82fGNt1TNE+GGVXKuQQ0N2nTO+iJETE69PiHnaAkkOzovM177OosxbKjpt3KvwuJflgUB2YGvgjk='
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
test_remote.state = 'online';
Message.verifyHashSignature(data, test_remote, function(err, valid){
assert(/account|address/i.test(err.message));
done();
});
});
it('should respond with an error if the signature is missing or invalid', function(done){
var data = {
message: 'Hello world!',
hash: '861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8',
account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz'
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
test_remote.state = 'online';
Message.verifyHashSignature(data, test_remote, function(err, valid){
assert(/signature/i.test(err.message));
done();
});
});
it('should respond true if the signature is valid and corresponds to an active public key for the account', function(done){
var data = {
message: 'Hello world!',
hash: 'e9a82ea40514787918959b1100481500a5d384030f8770575c6a587675025fe212e6623e25643f251666a7b8b23af476c2850a8ea92153de5724db432892c752',
account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
signature: 'AAAAHMIPCQGLgdnpX1Ccv1wHb56H4NggxIM6U08Qkb9mUjN2Vn9pZ3CHvq1yWLBi6NqpW+7kedLnmfu4VG2+y43p4Xs='
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
test_remote.state = 'online';
test_remote.request_account_info = function(account, callback) {
if (account === data.account) {
callback(null, {
"account_data": {
"Account": "rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz",
"Flags": 1114112,
"LedgerEntryType": "AccountRoot",
"RegularKey": "rHq2wyUtLkAad3vURUk33q9gozd97skhSf"
}
});
} else {
callback(new Error('wrong account'));
}
};
Message.verifyHashSignature(data, test_remote, function(err, valid){
assert(!err);
assert(valid);
done();
});
});
it('should respond false if a key can be recovered from the signature but it does not correspond to an active public key', function(done){
// Signature created by disabled master key
var data = {
message: 'Hello world!',
hash: 'e9a82ea40514787918959b1100481500a5d384030f8770575c6a587675025fe212e6623e25643f251666a7b8b23af476c2850a8ea92153de5724db432892c752',
account: 'rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz',
signature: 'AAAAG+dB/rAjZ5m8eQ/opcqQOJsFbKxOu9jq9KrOAlNO4OdcBDXyCBlkZqS9Xr8oZI2uh0boVsgYOS3pOLJz+Dh3Otk='
};
//Remote.prototype.addServer = function(){};
var test_remote = new Remote();
test_remote.state = 'online';
test_remote.request_account_info = function(account, callback) {
if (account === data.account) {
callback(null, {
"account_data": {
"Account": "rKXCummUHnenhYudNb9UoJ4mGBR75vFcgz",
"Flags": 1114112,
"LedgerEntryType": "AccountRoot",
"RegularKey": "rHq2wyUtLkAad3vURUk33q9gozd97skhSf"
}
});
} else {
callback(new Error('wrong account'));
}
};
Message.verifyHashSignature(data, test_remote, function(err, valid){
assert(!err);
assert(!valid);
done();
});
});
});
});

332
test/remote-test.js Normal file
View File

@@ -0,0 +1,332 @@
var assert = require('assert');
var utils = require('./testutils');
var Remote = utils.load_module('remote').Remote;
var Server = utils.load_module('server').Server;
var Request = utils.load_module('request').Request;
var options, spy, mock, stub, remote, callback, database, tx;
describe('Remote', function () {
beforeEach(function () {
options = {
trace : true,
trusted: true,
local_signing: true,
servers: [
{ host: 's-west.ripple.com', port: 443, secure: true },
{ host: 's-east.ripple.com', port: 443, secure: true }
],
blobvault : 'https://blobvault.payward.com',
persistent_auth : false,
transactions_per_page: 50,
bridge: {
out: {
// 'bitcoin': 'localhost:3000'
// 'bitcoin': 'https://www.bitstamp.net/ripple/bridge/out/bitcoin/'
}
},
};
})
describe('remote server initialization - url object', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: 443, secure: true } ],
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'wss://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url object - no secure property', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: 443 } ]
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'wss://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url object - secure: false', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: 443, secure: false } ]
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'ws://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url object - string port', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: '443', secure: true } ]
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'wss://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url object - invalid host', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ { host: '+', port: 443, secure: true } ]
});
}, Error);
done();
})
});
describe('remote server initialization - url object - invalid port', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: null, secure: true } ]
});
}, TypeError);
done();
})
});
describe('remote server initialization - url object - port out of range', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ { host: 's-west.ripple.com', port: 65537, secure: true } ]
});
}, Error);
done();
})
});
describe('remote server initialization - url string', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ 'wss://s-west.ripple.com:443' ]
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'wss://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url string - ws://', function() {
it('should construct url', function (done) {
var remote = new Remote({
servers: [ 'ws://s-west.ripple.com:443' ]
});
assert(Array.isArray(remote._servers));
assert(remote._servers[0] instanceof Server);
assert.strictEqual(remote._servers[0]._url, 'ws://s-west.ripple.com:443');
done();
})
});
describe('remote server initialization - url string - invalid host', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ 'ws://+:443' ]
});
}, Error
);
done();
})
});
describe('remote server initialization - url string - invalid port', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ 'ws://s-west.ripple.com:null' ]
});
}, Error
);
done();
})
});
describe('remote server initialization - url string - port out of range', function() {
it('should construct url', function (done) {
assert.throws(
function() {
var remote = new Remote({
servers: [ 'ws://s-west.ripple.com:65537:' ]
});
}, Error
);
done();
})
});
describe('request constructors', function () {
beforeEach(function () {
callback = function () {}
remote = new Remote(options);
});
describe('requesting a ledger', function () {
it('should return a request', function (done) {
var request = remote.request_ledger(null, {}, callback);
assert(request instanceof Request);
done();
})
});
describe('requesting server info', function () {
it('should return a request object', function (done) {
var request = remote.request_server_info(null, {}, callback);
assert(request instanceof Request);
done();
})
})
describe('requesting peers', function () {
it('should return a request object', function (done) {
var request = remote.request_peers(null, {}, callback);
assert(request instanceof Request);
done();
});
});
describe('requesting a connection', function () {
it('should return a request object', function (done) {
var request = remote.request_connect(null, {}, callback);
assert(request instanceof Request);
done();
});
});
describe('making a unique node list add request', function () {
it('should return a request object', function (done) {
var request = remote.request_unl_add(null, {}, callback);
assert(request instanceof Request);
done();
});
});
describe('making a unique node list request', function () {
it('should return a request object', function (done) {
var request = remote.request_unl_list(null, {}, callback);
assert(request instanceof Request);
done();
});
});
describe('making a unique node list delete request', function () {
it('should return a request object', function (done) {
var request = remote.request_unl_delete(null, {}, callback);
assert(request instanceof Request);
done();
});
});
})
describe('create remote and get pending transactions', function() {
before(function() {
tx = [{
tx_json: {
Account : "r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS",
Amount : {
currency : "LTC",
issuer : "r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS",
value : "9.985"
},
Destination : "r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS",
Fee : "15",
Flags : 0,
Paths : [
[
{
account : "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q",
currency : "USD",
issuer : "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q",
type : 49,
type_hex : "0000000000000031"
},
{
currency : "LTC",
issuer : "rfYv1TXnwgDDK4WQNbFALykYuEBnrR4pDX",
type : 48,
type_hex : "0000000000000030"
},
{
account : "rfYv1TXnwgDDK4WQNbFALykYuEBnrR4pDX",
currency : "LTC",
issuer : "rfYv1TXnwgDDK4WQNbFALykYuEBnrR4pDX",
type : 49,
type_hex : "0000000000000031"
}
]
],
SendMax : {
currency : "USD",
issuer : "r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS",
value : "30.30993068"
},
Sequence : 415,
SigningPubKey : "02854B06CE8F3E65323F89260E9E19B33DA3E01B30EA4CA172612DE77973FAC58A",
TransactionType : "Payment",
TxnSignature : "304602210096C2F385530587DE573936CA51CB86B801A28F777C944E268212BE7341440B7F022100EBF0508A9145A56CDA7FAF314DF3BBE51C6EE450BA7E74D88516891A3608644E"
},
clientID: '48631',
state: 'pending',
submitIndex: 1,
submittedIDs: ["304602210096C2F385530587DE573936CA51CB86B801A28F777C944E268212BE7341440B7F022100EBF0508A9145A56CDA7FAF314DF3BBE51C6EE450BA7E74D88516891A3608644E"],
secret: 'mysecret'
}];
database = {
getPendingTransactions: function(callback) {
callback(null, tx);
}
}
})
it('should set transaction members correct ', function(done) {
remote = new Remote(options);
remote.storage = database;
remote.transaction = function() {
return {
clientID: function(id) {
if (typeof id === 'string') {
this._clientID = id;
}
return this;
},
submit: function() {
assert.deepEqual(this._clientID, tx[0].clientID);
assert.deepEqual(this.submittedIDs,[tx[0].tx_json.TxnSignature]);
assert.equal(this.submitIndex, tx[0].submitIndex);
assert.equal(this.secret, tx[0].secret);
done();
},
parseJson: function(json) {}
}
}
remote.getPendingTransactions();
})
})
})

676
test/request-test.js Normal file
View File

@@ -0,0 +1,676 @@
var assert = require('assert');
var utils = require('./testutils');
var Request = utils.load_module('request').Request;
var Remote = utils.load_module('remote').Remote;
var Server = utils.load_module('server').Server;
function makeServer(url) {
var server = new Server(new process.EventEmitter(), url);
server._connected = true;
return server;
};
const SERVER_INFO = {
'info': {
'build_version': '0.25.2-rc1',
'complete_ledgers': '32570-7016339',
'hostid': 'LIED',
'io_latency_ms': 1,
'last_close': {
'converge_time_s': 2.013,
'proposers': 5
},
'load_factor': 1,
'peers': 42,
'pubkey_node': 'n9LpxYuMx4Epz4Wz8Kg2kH3eBTx1mUtHnYwtCdLoj3HC85L2pvBm',
'server_state': 'full',
'validated_ledger': {
'age': 0,
'base_fee_xrp': 0.00001,
'hash': 'E43FD49087B18031721D9C3C4743FE1692C326AFF7084A2C01B355CE65A4C699',
'reserve_base_xrp': 20,
'reserve_inc_xrp': 5,
'seq': 7016339
},
'validation_quorum': 3
}
};
describe('Request', function() {
it('Send request', function(done) {
var remote = {
request: function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
done();
}
};
var request = new Request(remote, 'server_info');
request.request();
// Should only request once
request.request();
});
it('Broadcast request', function(done) {
var servers = [
makeServer('wss://localhost:5006'),
makeServer('wss://localhost:5007')
];
var requests = 0;
servers.forEach(function(server, index, arr) {
server._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
if (++requests === arr.length) {
done();
}
};
});
var remote = new Remote();
remote._connected = true;
remote._servers = servers;
var request = new Request(remote, 'server_info');
request.broadcast();
});
it('Events API', function(done) {
var server = makeServer('wss://localhost:5006');
server._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
req.emit('success', SERVER_INFO);
};
var remote = new Remote();
remote._connected = true;
remote._servers = [ server ];
var request = new Request(remote, 'server_info');
request.once('success', function(res) {
assert.deepEqual(res, SERVER_INFO);
done();
});
request.request();
});
it('Callback API', function(done) {
var server = makeServer('wss://localhost:5006');
server._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
req.emit('success', SERVER_INFO);
};
var remote = new Remote();
remote._connected = true;
remote._servers = [ server ];
var request = new Request(remote, 'server_info');
request.callback(function(err, res) {
assert.ifError(err);
assert.deepEqual(res, SERVER_INFO);
done();
});
});
it('Timeout', function(done) {
var server = makeServer('wss://localhost:5006');
var successEmited = false;
server._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
setTimeout(function() {
successEmitted = true;
req.emit('success', SERVER_INFO);
}, 200);
};
var remote = new Remote();
remote._connected = true;
remote._servers = [ server ];
var request = new Request(remote, 'server_info');
request.timeout(10, function() {
setTimeout(function() {
assert(successEmitted);
done();
}, 200);
});
request.callback(function(err, res) {
assert(false, 'Callback should not be called');
});
});
it('Timeout - satisfied', function(done) {
var server = makeServer('wss://localhost:5006');
var successEmited = false;
server._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
setTimeout(function() {
successEmitted = true;
req.emit('success', SERVER_INFO);
}, 200);
};
var remote = new Remote();
remote._connected = true;
remote._servers = [ server ];
var request = new Request(remote, 'server_info');
var timedOut = false;
request.once('timeout', function() {
timedOut = true;
});
request.timeout(1000);
request.callback(function(err, res) {
assert(!timedOut);
assert.ifError(err);
assert.deepEqual(res, SERVER_INFO);
done();
});
});
it('Set server', function(done) {
var servers = [
makeServer('wss://localhost:5006'),
makeServer('wss://localhost:5007')
];
servers[1]._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
done();
};
var remote = new Remote();
remote._connected = true;
remote._servers = servers;
remote.getServer = function() {
return servers[0];
};
var request = new Request(remote, 'server_info');
request.setServer(servers[1]);
assert.strictEqual(request.server, servers[1]);
request.request();
});
it('Set server - by URL', function(done) {
var servers = [
makeServer('wss://localhost:5006'),
makeServer('wss://127.0.0.1:5007')
];
servers[1]._request = function(req) {
assert(req instanceof Request);
assert.strictEqual(typeof req.message, 'object');
assert.strictEqual(req.message.command, 'server_info');
done();
};
var remote = new Remote();
remote._connected = true;
remote._servers = servers;
remote.getServer = function() {
return servers[0];
};
var request = new Request(remote, 'server_info');
request.setServer('wss://127.0.0.1:5007');
assert.strictEqual(request.server, servers[1]);
request.request();
});
it('Set build path', function() {
var remote = new Remote();
remote._connected = true;
remote.local_signing = false;
var request = new Request(remote, 'server_info');
request.buildPath(true);
assert.strictEqual(request.message.build_path, true);
});
it('Remove build path', function() {
var remote = new Remote();
remote._connected = true;
remote.local_signing = false;
var request = new Request(remote, 'server_info');
request.buildPath(false);
assert(!request.message.hasOwnProperty('build_path'));
});
it('Set build path with local signing', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
assert.throws(function() {
request.buildPath(true);
}, Error);
});
it('Set ledger hash', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerHash('B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
assert.strictEqual(request.message.ledger_hash, 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
});
it('Set ledger index', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerIndex(7016915);
assert.strictEqual(request.message.ledger_index, 7016915);
});
it('Select cached ledger - index', function() {
var remote = new Remote();
remote._connected = true;
remote._ledger_current_index = 1;
remote._ledger_hash = 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE';
var request = new Request(remote, 'server_info');
request.ledgerChoose(true);
assert.strictEqual(request.message.ledger_index, 1);
});
it('Select cached ledger - hash', function() {
var remote = new Remote();
remote._connected = true;
remote._ledger_current_index = 1;
remote._ledger_hash = 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE';
var request = new Request(remote, 'server_info');
request.ledgerChoose();
assert.strictEqual(request.message.ledger_hash, 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
});
it('Select ledger - identifier', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerSelect('validated');
assert.strictEqual(request.message.ledger_index, 'validated');
});
it('Select ledger - index', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerSelect(7016915);
assert.strictEqual(request.message.ledger_index, 7016915);
});
it('Select ledger - hash', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerSelect('B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
assert.strictEqual(request.message.ledger_hash, 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
});
it('Select ledger - hash', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.ledgerSelect('B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
assert.strictEqual(request.message.ledger_hash, 'B4FD84A73DBD8F0DA9E320D137176EBFED969691DC0AAC7882B76B595A0841AE');
});
it('Set account_root', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accountRoot('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59');
assert.strictEqual(request.message.account_root, 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59');
});
it('Set index', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.index(1);
assert.strictEqual(request.message.index, 1);
});
it('Set offer ID', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.offerId('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 1337);
assert.deepEqual(request.message.offer, {
account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
seq: 1337
});
});
it('Set offer index', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.offerIndex(1337);
assert.strictEqual(request.message.offer, 1337);
});
it('Set secret', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.secret('mySecret');
assert.strictEqual(request.message.secret, 'mySecret');
});
it('Set transaction hash', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.txHash('E08D6E9754025BA2534A78707605E0601F03ACE063687A0CA1BDDACFCD1698C7');
assert.strictEqual(request.message.tx_hash, 'E08D6E9754025BA2534A78707605E0601F03ACE063687A0CA1BDDACFCD1698C7');
});
it('Set transaction JSON', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
var txJson = { hash: 'E08D6E9754025BA2534A78707605E0601F03ACE063687A0CA1BDDACFCD1698C7' };
request.txJson(txJson);
assert.deepEqual(request.message.tx_json, txJson);
});
it('Set transaction blob', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.txBlob('asdf');
assert.strictEqual(request.message.tx_blob, 'asdf');
});
it('Set ripple state', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.rippleState('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 'USD');
assert.deepEqual(request.message.ripple_state, {
currency: 'USD',
accounts: [ 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59' ]
});
});
it('Set accounts', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accounts([
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
assert.deepEqual(request.message.accounts, [
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
});
it('Set accounts - string', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accounts('rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun');
assert.deepEqual(request.message.accounts, [
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun'
]);
});
it('Set accounts proposed', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accountsProposed([
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
assert.deepEqual(request.message.accounts_proposed, [
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
});
it('Add account', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accounts([
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
]);
request.addAccount('rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
assert.deepEqual(request.message.accounts, [
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
});
it('Add account proposed', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.accountsProposed([
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
]);
request.addAccountProposed('rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B');
assert.deepEqual(request.message.accounts_proposed, [
'rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun',
'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
]);
});
it('Set books', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
var books = [
{
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
}
];
request.books(books);
assert.deepEqual(request.message.books, books);
});
it('Add book', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.addBook({
'taker_gets': {
'currency': 'CNY',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
});
assert.deepEqual(request.message.books, [
{
'taker_gets': {
'currency': 'CNY',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
}
]);
var books = [
{
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
}
];
request.books(books);
assert.deepEqual(request.message.books, [
{
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
},
]);
});
it('Add book - missing side', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.message.books = void(0);
var books = [
{
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
}
}
];
assert.throws(function() {
request.books(books);
});
});
it('Add book - with snapshot', function() {
var remote = new Remote();
remote._connected = true;
var request = new Request(remote, 'server_info');
request.message.books = void(0);
var book = {
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'both': true
};
request.addBook(book, true);
assert.deepEqual(request.message.books, [{
'taker_gets': {
'currency': 'EUR',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'taker_pays': {
'currency': 'USD',
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
},
'snapshot': true,
'both': true
}]);
});
});

63
test/seed-test.js Normal file
View File

@@ -0,0 +1,63 @@
var assert = require('assert');
var utils = require('./testutils');
var Seed = utils.load_module('seed').Seed;
var config = require('./testutils').get_config();
describe('Seed', function() {
it('can generate many addresses', function () {
var seed = Seed.from_json("masterpassphrase");
// Note: Created with jRippleAPI code
// Link: https://github.com/pmarches/jRippleAPI/blob/master/src/jrippleapi/keys/RippleDeterministicKeyGenerator.java
// To reviewer/merger: Even generating keypairs for thi this small amount of
// addresses makes the test suite run SO SLOW. Consider cutting at the tail.
var first_nth_addresses = [
// 0th implied
"rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh",
// 1th implied
"r4bYF7SLUMD7QgSLLpgJx38WJSY12ViRjP",
// 2th implied
"rLpAd4peHUMBPbVJASMYK5GTBUSwXRD9nx",
// ...
"rN9HWHPAftXC6xNxJRqgVr1HexpUi6FBUa",
"rhwPfeEkeQh2vqoKGPBpPyS9nKmKZdpypu",
"rKdNfPfrzfisDCPCqK67YhDLezuVKGKXNm",
"rsn4NeGzMRvMn5ABQxmt9VNEkSknVneBK4",
"rUSJGFH1kQnaKpoAhkArfyw6HZVe8GT5w3",
"r3EYp6isx2Row5pu19C4Ujvp68oEEabhuA",
"rGiYpnAn9DTXiM78CCJcYAuL6QHEDdazHA",
"rVrRVeqqEJHAove5B9TqBAHEXBTzMi5eu",
"rJbarThDXYXxtCgDxRoTCDf2NoYdgSjuVk",
"rfuWNJ1TkQzoZZcc4K8wmtsUiGwURFbed1",
"rpuTqebfbZZdKEUV3bjecoViNL4W4gepWZ",
"r42ywHUco4C2AjgaSmYM7uX13Kbz6GdDKp",
"rnWb45MLd5hQiB6Arr94DdY2z95quL7XNf",
"rMukaQ87bfAeddcT16RtgS3RbFmaQWrSGu",
"rN6dMHU51K9y8eVMhjQMsQVp5gPwt3eYYx",
"rfRFyeJDNqpfZVFmjNj9tNzFVsCNAWKtNc",
"rMoGSX48KrT31HKx9KfMSnYhjvRw3YYzQW",
"rfTiEfbeVsYU7QEe1Zfogiz7h43x6ChKGC"
]
function assert_helper(account_id, expected) {
var keypair = seed.get_key(account_id);
assert.strictEqual(keypair.get_address().to_json(),
expected);
}
for (var nth = 0; nth < first_nth_addresses.length; nth++) {
var expected = first_nth_addresses[nth], looking_for;
//`seed.get_key($ripple_address)` is arguably an ill concieved feature
// as it needs to generate `nth` many keypairs and generate hashed public
// keys (addresses) for equality tests ??
// Would need remote.set_secret(address, private_key_not_seed) ??
assert_helper((looking_for = expected), expected)
// This isn't too bad as it only needs to generate one keypair `seq`
assert_helper((looking_for = nth), expected)
};
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -0,0 +1,94 @@
var utils = require('./testutils');
var assert = require('assert');
var SerializedObject = utils.load_module('serializedobject').SerializedObject;
describe('Serialized object', function() {
describe('#from_json(v).to_json() == v', function(){
it('outputs same as passed to from_json', function() {
var input_json = {
Account: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Amount: '274579388',
Destination: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Fee: '15',
Flags: 0,
Paths: [[
{
account: 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV',
currency: 'USD',
issuer: 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV'
},
{
currency: 'XRP'
}
]],
SendMax: {
currency: 'USD',
issuer: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
value: '2.74579388'
},
Sequence: 351,
SigningPubKey: '02854B06CE8F3E65323F89260E9E19B33DA3E01B30EA4CA172612DE77973FAC58A',
TransactionType: 'Payment',
TxnSignature: '30450221009DA3A42DD25E3B22EC45AD8BA8FC7A954264264A816D300B2DF69F814D7D4DD2022072C9627F97EEC6DA13DE841E06E2CD985EF06A0FBB15DDBF0800D0730C8986BF'
};
var output_json = SerializedObject.from_json(input_json).to_json();
assert.deepEqual(input_json, output_json);
});
});
describe('#from_json', function() {
it('understands TransactionType as a Number', function() {
var input_json = {
// no non required fields
Account: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Amount: '274579388',
Destination: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Fee: '15',
Sequence: 351,
SigningPubKey: '02',// VL field ;)
TransactionType: 0 //
};
var output_json = SerializedObject.from_json(input_json).to_json();
assert.equal(0, input_json.TransactionType);
assert.equal("Payment", output_json.TransactionType);
});
it('understands LedgerEntryType as a Number', function() {
var input_json = {
// no, non required fields
"LedgerEntryType": 100,
"Flags": 0,
"Indexes": [],
"RootIndex": "000360186E008422E06B72D5B275E29EE3BE9D87A370F424E0E7BF613C465909"
}
var output_json = SerializedObject.from_json(input_json).to_json();
assert.equal(100, input_json.LedgerEntryType);
assert.equal("DirectoryNode", output_json.LedgerEntryType);
});
describe('Format validation', function() {
// Peercover actually had a problem submitting transactions without a `Fee`
// and rippled was only informing of "transaction is invalid"
it('should throw an Error when there is a missing field', function() {
var input_json = {
Account: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Amount: '274579388',
Destination: 'r4qLSAzv4LZ9TLsR7diphGwKnSEAMQTSjS',
Sequence: 351,
SigningPubKey: '02854B06CE8F3E65323F89260E9E19B33DA3E01B30EA4CA172612DE77973FAC58A',
TransactionType: 'Payment',
TxnSignature: '30450221009DA3A42DD25E3B22EC45AD8BA8FC7A954264264A816D300B2DF69F814D7D4DD2022072C9627F97EEC6DA13DE841E06E2CD985EF06A0FBB15DDBF0800D0730C8986BF'
};
assert.throws (
function() {
var output_json = SerializedObject.from_json(input_json);
},
/Payment is missing fields: \["Fee"\]/
);
});
});
})
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -0,0 +1,907 @@
var utils = require('./testutils');
var assert = require('assert');
var SerializedObject = utils.load_module('serializedobject').SerializedObject;
var types = utils.load_module('serializedtypes');
var BigInteger = require('../src/js/jsbn/jsbn').BigInteger;
var config = require('./testutils').get_config();
describe('Serialized types', function() {
describe('Int8', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Int8.serialize(so, 0);
assert.strictEqual(so.to_hex(), '00');
});
it('Serialize 123', function () {
var so = new SerializedObject();
types.Int8.serialize(so, 123);
assert.strictEqual(so.to_hex(), '7B');
});
it('Serialize 255', function () {
var so = new SerializedObject();
types.Int8.serialize(so, 255);
assert.strictEqual(so.to_hex(), 'FF');
});
it('Fail to serialize 256', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, 256);
});
});
it('Fail to serialize -1', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, -1);
});
});
it('Serialize 5.5 (should floor)', function () {
var so = new SerializedObject();
types.Int8.serialize(so, 5.5);
assert.strictEqual(so.to_hex(), '05');
});
it('Serialize 255.9 (should floor)', function () {
var so = new SerializedObject();
types.Int8.serialize(so, 255.9);
assert.strictEqual(so.to_hex(), 'FF');
});
it('Fail to serialize null', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, null);
});
});
it('Fail to serialize "bla"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, 'bla');
});
});
it('Fail to serialize {}', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, {});
});
});
});
describe('Int16', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 0);
assert.strictEqual(so.to_hex(), '0000');
});
it('Serialize 123', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 123);
assert.strictEqual(so.to_hex(), '007B');
});
it('Serialize 255', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 255);
assert.strictEqual(so.to_hex(), '00FF');
});
it('Serialize 256', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 256);
assert.strictEqual(so.to_hex(), '0100');
});
it('Serialize 65535', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 65535);
assert.strictEqual(so.to_hex(), 'FFFF');
});
it('Fail to serialize 65536', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, 65536);
});
});
it('Fail to serialize -1', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int16.serialize(so, -1);
});
});
it('Serialize 123.5 (should floor)', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 123.5);
assert.strictEqual(so.to_hex(), '007B');
});
it('Serialize 65535.5 (should floor)', function () {
var so = new SerializedObject();
types.Int16.serialize(so, 65535.5);
assert.strictEqual(so.to_hex(), 'FFFF');
});
it('Fail to serialize null', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int16.serialize(so, null);
});
});
it('Fail to serialize "bla"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int16.serialize(so, 'bla');
});
});
it('Fail to serialize {}', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int16.serialize(so, {});
});
});
});
describe('Int32', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 0);
assert.strictEqual(so.to_hex(), '00000000');
});
it('Serialize 123', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 123);
assert.strictEqual(so.to_hex(), '0000007B');
});
it('Serialize 255', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 255);
assert.strictEqual(so.to_hex(), '000000FF');
});
it('Serialize 256', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 256);
assert.strictEqual(so.to_hex(), '00000100');
});
it('Serialize 0xF0F0F0F0', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 0xF0F0F0F0);
assert.strictEqual(so.to_hex(), 'F0F0F0F0');
});
it('Serialize 0xFFFFFFFF', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 0xFFFFFFFF);
assert.strictEqual(so.to_hex(), 'FFFFFFFF');
});
it('Fail to serialize 0x100000000', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, 0x100000000);
});
});
it('Fail to serialize -1', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int32.serialize(so, -1);
});
});
it('Serialize 123.5 (should floor)', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 123.5);
assert.strictEqual(so.to_hex(), '0000007B');
});
it('Serialize 4294967295.5 (should floor)', function () {
var so = new SerializedObject();
types.Int32.serialize(so, 4294967295.5);
assert.strictEqual(so.to_hex(), 'FFFFFFFF');
});
it('Fail to serialize null', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int32.serialize(so, null);
});
});
it('Fail to serialize "bla"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int32.serialize(so, 'bla');
});
});
it('Fail to serialize {}', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int32.serialize(so, {});
});
});
it('Parse 0', function () {
var val = '00000000';
var so = new SerializedObject(val);
var num = types.Int32.parse(so);
assert.strictEqual(num, parseInt(val, 16));
});
it('Parse 1', function () {
var val = '00000001';
var so = new SerializedObject(val);
var num = types.Int32.parse(so);
assert.strictEqual(num, parseInt(val, 16));
});
it('Parse UINT32_MAX', function () {
var val = 'FFFFFFFF';
var so = new SerializedObject(val);
var num = types.Int32.parse(so);
assert.strictEqual(num, parseInt(val, 16));
});
});
describe('Int64', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 0);
assert.strictEqual(so.to_hex(), '0000000000000000');
});
it('Serialize 123', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 123);
assert.strictEqual(so.to_hex(), '000000000000007B');
});
it('Serialize 255', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 255);
assert.strictEqual(so.to_hex(), '00000000000000FF');
});
it('Serialize 256', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 256);
assert.strictEqual(so.to_hex(), '0000000000000100');
});
it('Serialize 0xF0F0F0F0', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 0xF0F0F0F0);
assert.strictEqual(so.to_hex(), '00000000F0F0F0F0');
});
it('Serialize 0xFFFFFFFF', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 0xFFFFFFFF);
assert.strictEqual(so.to_hex(), '00000000FFFFFFFF');
});
it('Serialize 0x100000000', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 0x100000000);
assert.strictEqual(so.to_hex(), '0000000100000000');
});
it('Fail to serialize 0x100000000', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int8.serialize(so, 0x100000000);
});
});
it('Fail to serialize -1', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, -1);
});
});
it('Serialize 123.5 (should floor)', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 123.5);
assert.strictEqual(so.to_hex(), '000000000000007B');
});
it('Serialize 4294967295.5 (should floor)', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 4294967295.5);
assert.strictEqual(so.to_hex(), '00000000FFFFFFFF');
});
it('Does not get confused when the high bit is set', function () {
var so = new SerializedObject();
types.Int64.serialize(so, "8B2386F26F8E232B");
assert.strictEqual(so.to_hex(), '8B2386F26F8E232B');
var so = new SerializedObject("8B2386F26F8E232B");
var num = types.Int64.parse(so);
// We get a positive number
assert.strictEqual(num.toString(16), '8b2386f26f8e232b');
});
it('Serialize "0123456789ABCDEF"', function () {
var so = new SerializedObject();
types.Int64.serialize(so, '0123456789ABCDEF');
assert.strictEqual(so.to_hex(), '0123456789ABCDEF');
});
it('Serialize "F0E1D2C3B4A59687"', function () {
var so = new SerializedObject();
types.Int64.serialize(so, 'F0E1D2C3B4A59687');
assert.strictEqual(so.to_hex(), 'F0E1D2C3B4A59687');
});
it('Serialize BigInteger("FFEEDDCCBBAA9988")', function () {
var so = new SerializedObject();
types.Int64.serialize(so, new BigInteger('FFEEDDCCBBAA9988', 16));
assert.strictEqual(so.to_hex(), 'FFEEDDCCBBAA9988');
});
it('Fail to serialize BigInteger("-1")', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, new BigInteger('-1', 10));
});
});
it('Fail to serialize "10000000000000000"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, '10000000000000000');
});
});
it('Fail to serialize "110000000000000000"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, '110000000000000000');
});
});
it('Fail to serialize null', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, null);
});
});
it('Fail to serialize "bla"', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, 'bla');
});
});
it('Fail to serialize {}', function () {
var so = new SerializedObject();
assert.throws(function () {
types.Int64.serialize(so, {});
});
});
it('Parse "0123456789ABCDEF"', function () {
var so = new SerializedObject("0123456789ABCDEF");
var num = types.Int64.parse(so);
assert.strictEqual(num.toString(10), '81985529216486895');
});
});
describe('Hash128', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Hash128.serialize(so, '00000000000000000000000000000000');
assert.strictEqual(so.to_hex(), '00000000000000000000000000000000');
});
it('Serialize 102030405060708090A0B0C0D0E0F000', function () {
var so = new SerializedObject();
types.Hash128.serialize(so, '102030405060708090A0B0C0D0E0F000');
assert.strictEqual(so.to_hex(), '102030405060708090A0B0C0D0E0F000');
});
it('Serialize HASH128_MAX', function () {
var so = new SerializedObject();
types.Hash128.serialize(so, 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
assert.strictEqual(so.to_hex(), 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
});
it('Parse 0', function () {
var val = '00000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Hash128.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse 1', function () {
var val = '00000000000000000000000000000001';
var so = new SerializedObject(val);
var num = types.Hash128.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse HASH128_MAX', function () {
var val = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var so = new SerializedObject(val);
var num = types.Hash128.parse(so);
assert.strictEqual(num.to_hex(), val);
});
});
describe('Hash160', function() {
it('Serialize 0', function () {
var hex = '0000000000000000000000000000000000000000';
var base58 = 'rrrrrrrrrrrrrrrrrrrrrhoLvTp';
var so = new SerializedObject();
types.Hash160.serialize(so, base58);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject();
types.Hash160.serialize(so, hex);
assert.strictEqual(so.to_hex(), hex);
});
it('Serialize 1', function () {
var hex = '0000000000000000000000000000000000000001';
var base58 = 'rrrrrrrrrrrrrrrrrrrrBZbvji';
var so = new SerializedObject();
types.Hash160.serialize(so, base58);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject();
types.Hash160.serialize(so, hex);
assert.strictEqual(so.to_hex(), hex);
});
it('Serialize FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', function () {
var hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var base58 = 'rQLbzfJH5BT1FS9apRLKV3G8dWEA5njaQi';
var so = new SerializedObject();
types.Hash160.serialize(so, base58);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject();
types.Hash160.serialize(so, hex);
assert.strictEqual(so.to_hex(), hex);
});
it('Parse 0', function () {
var val = '0000000000000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Hash160.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse 1', function () {
var val = '0000000000000000000000000000000000000001';
var so = new SerializedObject(val);
var num = types.Hash160.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse HASH160_MAX', function () {
var val = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var so = new SerializedObject(val);
var num = types.Hash160.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse 0 as JSON', function () {
// Hash160 should be returned as hex in JSON, unlike
// addresses.
var val = '0000000000000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Hash160.parse(so);
assert.strictEqual(num.to_json(), val);
});
});
describe('Hash256', function() {
it('Serialize 0', function () {
var so = new SerializedObject();
types.Hash256.serialize(so, '0000000000000000000000000000000000000000000000000000000000000000');
assert.strictEqual(so.to_hex(), '0000000000000000000000000000000000000000000000000000000000000000');
});
it('Serialize 1', function () {
var so = new SerializedObject();
types.Hash256.serialize(so, '0000000000000000000000000000000000000000000000000000000000000001');
assert.strictEqual(so.to_hex(), '0000000000000000000000000000000000000000000000000000000000000001');
});
it('Serialize HASH256_MAX', function () {
var so = new SerializedObject();
types.Hash256.serialize(so, 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
assert.strictEqual(so.to_hex(), 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
});
it('Parse 0', function () {
var val = '0000000000000000000000000000000000000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Hash256.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse 1', function () {
var val = '0000000000000000000000000000000000000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Hash256.parse(so);
assert.strictEqual(num.to_hex(), val);
});
it('Parse HASH256_MAX', function () {
var val = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var so = new SerializedObject(val);
var num = types.Hash256.parse(so);
assert.strictEqual(num.to_hex(), val);
});
});
describe('Amount', function() {
it('Serialize 0 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '0');
assert.strictEqual(so.to_hex(), '4000000000000000');
});
it('Serialize 1 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '1');
assert.strictEqual(so.to_hex(), '4000000000000001');
});
it('Serialize -1 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '-1');
assert.strictEqual(so.to_hex(), '0000000000000001');
});
it('Serialize 213 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '213');
assert.strictEqual(so.to_hex(), '40000000000000D5');
});
it('Serialize 270544960 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '270544960');
assert.strictEqual(so.to_hex(), '4000000010203040');
});
it('Serialize 1161981756646125568 XRP', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '1161981756646125696');
assert.strictEqual(so.to_hex(), '5020304050607080');
});
it('Serialize 1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
assert.strictEqual(so.to_hex(), 'D4838D7EA4C680000000000000000000000000005553440000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
});
it('Serialize 87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
assert.strictEqual(so.to_hex(), 'D65F241D335BF24E0000000000000000000000004555520000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
});
it('Serialize -1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject();
types.Amount.serialize(so, '-1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
assert.strictEqual(so.to_hex(), '94838D7EA4C680000000000000000000000000005553440000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
});
it('Serialize 15/XRP/rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo', function () {
// This actually appears in the ledger, so we need to be able to serialize
// Transaction #A2AD66C93C7B7277CD5AEB718A4E82D88C7099129948BC66A394EE38B34657A9
var so = new SerializedObject();
types.Amount.serialize(so, {
"value":"1000",
"currency":"XRP",
"issuer":"rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo"
});
assert.strictEqual(so.to_hex(), 'D5438D7EA4C680000000000000000000000000005852500000000000E4FE687C90257D3D2D694C8531CDEECBE84F3367');
});
// Test support for 20-byte hex raw currency codes
it('Serialize 15/015841551A748AD23FEFFFFFFFEA028000000000/1', function () {
var so = new SerializedObject();
types.Amount.serialize(so, {
"value":"1000",
"currency":"015841551A748AD23FEFFFFFFFEA028000000000",
"issuer":"rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo"
});
assert.strictEqual(so.to_hex(), 'D5438D7EA4C68000015841551A748AD23FEFFFFFFFEA028000000000E4FE687C90257D3D2D694C8531CDEECBE84F3367');
});
it('Parse 1 XRP', function () {
var so = new SerializedObject('4000000000000001');
assert.strictEqual(types.Amount.parse(so).to_json(), '1');
});
it('Parse -1 XRP', function () {
var so = new SerializedObject('0000000000000001');
assert.strictEqual(types.Amount.parse(so).to_json(), '-1');
});
it('Parse 213 XRP', function () {
var so = new SerializedObject('40000000000000D5');
assert.strictEqual(types.Amount.parse(so).to_json(), '213');
});
it('Parse 270544960 XRP', function () {
var so = new SerializedObject('4000000010203040');
assert.strictEqual(types.Amount.parse(so).to_json(), '270544960');
});
it('Parse 1161981756646125568 XRP', function () {
var so = new SerializedObject('5020304050607080');
assert.strictEqual(types.Amount.parse(so).to_json(), '1161981756646125696');
});
it('Parse 1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject('D4838D7EA4C680000000000000000000000000005553440000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
assert.strictEqual(types.Amount.parse(so).to_text_full(), '1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Parse 87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject('D65F241D335BF24E0000000000000000000000004555520000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
assert.strictEqual(types.Amount.parse(so).to_text_full(), '87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
it('Parse -1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var so = new SerializedObject('94838D7EA4C680000000000000000000000000005553440000000000B5F762798A53D543A014CAF8B297CFF8F2F937E8');
assert.strictEqual(types.Amount.parse(so).to_text_full(), '-1/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
});
});
describe('Account', function() {
it('Serialize 0', function () {
var hex = '0000000000000000000000000000000000000000';
var base58 = 'rrrrrrrrrrrrrrrrrrrrrhoLvTp';
var so = new SerializedObject();
types.Account.serialize(so, base58);
assert.strictEqual(so.to_hex(), "14"+hex);
so = new SerializedObject();
types.Account.serialize(so, hex);
assert.strictEqual(so.to_hex(), "14"+hex);
});
it('Serialize 1', function () {
var hex = '0000000000000000000000000000000000000001';
var base58 = 'rrrrrrrrrrrrrrrrrrrrBZbvji';
var so = new SerializedObject();
types.Account.serialize(so, base58);
assert.strictEqual(so.to_hex(), "14"+hex);
so = new SerializedObject();
types.Account.serialize(so, hex);
assert.strictEqual(so.to_hex(), "14"+hex);
});
it('Serialize FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', function () {
var hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var base58 = 'rQLbzfJH5BT1FS9apRLKV3G8dWEA5njaQi';
var so = new SerializedObject();
types.Account.serialize(so, base58);
assert.strictEqual(so.to_hex(), "14"+hex);
so = new SerializedObject();
types.Account.serialize(so, hex);
assert.strictEqual(so.to_hex(), "14"+hex);
});
it('Parse 0', function () {
var val = '140000000000000000000000000000000000000000';
var so = new SerializedObject(val);
var num = types.Account.parse(so);
assert.strictEqual(num.to_json(), 'rrrrrrrrrrrrrrrrrrrrrhoLvTp');
});
it('Parse 1', function () {
var val = '140000000000000000000000000000000000000001';
var so = new SerializedObject(val);
var num = types.Account.parse(so);
assert.strictEqual(num.to_json(), 'rrrrrrrrrrrrrrrrrrrrBZbvji');
});
it('Parse HASH160_MAX', function () {
var val = '14FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
var so = new SerializedObject(val);
var num = types.Account.parse(so);
assert.strictEqual(num.to_json(), 'rQLbzfJH5BT1FS9apRLKV3G8dWEA5njaQi');
});
});
describe('PathSet', function() {
it('Serialize single empty path [[]]', function () {
var so = new SerializedObject();
types.PathSet.serialize(so, [[]]);
assert.strictEqual(so.to_hex(), '00');
});
it('Serialize [[e],[e,e]]', function () {
var so = new SerializedObject();
types.PathSet.serialize(so, [[ {
account: 123,
currency: 'USD',
issuer: 789
}],
[{
account: 123,
currency: 'BTC',
issuer: 789
},
{
account: 987,
currency: 'EUR',
issuer: 321
}]]);
assert.strictEqual(so.to_hex(), '31000000000000000000000000000000000000007B00000000000000000000000055534400000000000000000000000000000000000000000000000315FF31000000000000000000000000000000000000007B000000000000000000000000425443000000000000000000000000000000000000000000000003153100000000000000000000000000000000000003DB0000000000000000000000004555520000000000000000000000000000000000000000000000014100'); //TODO: Check this independently
});
it('Serialize path through XRP', function () {
var hex = '31000000000000000000000000000000000000007B00000000000000000000000055534400000000000000000000000000000000000000000000000315FF1000000000000000000000000000000000000000003100000000000000000000000000000000000003DB0000000000000000000000004555520000000000000000000000000000000000000000000000014100';
var json = [
[ {
account: "rrrrrrrrrrrrrrrrrrrrNxV3Xza",
currency: 'USD',
issuer: "rrrrrrrrrrrrrrrrrrrpYnYCNYf"
}],
[{
currency: "XRP"
}, {
account: "rrrrrrrrrrrrrrrrrrrpvQsW3V3",
currency: 'EUR',
issuer: "rrrrrrrrrrrrrrrrrrrdHRtqg2"
}]
];
var so = new SerializedObject();
types.PathSet.serialize(so, json);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject(hex);
var parsed_path = SerializedObject.jsonify_structure(types.PathSet.parse(so));
assert.deepEqual(parsed_path, json);
});
it('Serialize path through XRP IOUs', function () {
var hex = '31000000000000000000000000000000000000007B00000000000000000000000055534400000000000000000000000000000000000000000000000315FF1000000000000000000000000058525000000000003100000000000000000000000000000000000003DB0000000000000000000000004555520000000000000000000000000000000000000000000000014100';
var json = [
[ {
account: "rrrrrrrrrrrrrrrrrrrrNxV3Xza",
currency: 'USD',
issuer: "rrrrrrrrrrrrrrrrrrrpYnYCNYf"
}],
[{
currency: "XRP",
non_native: true
}, {
account: "rrrrrrrrrrrrrrrrrrrpvQsW3V3",
currency: 'EUR',
issuer: "rrrrrrrrrrrrrrrrrrrdHRtqg2"
}]
];
var so = new SerializedObject();
types.PathSet.serialize(so, json);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject(hex);
var parsed_path = SerializedObject.jsonify_structure(types.PathSet.parse(so));
assert.deepEqual(parsed_path, json);
});
it('Serialize path through XRP IOUs (realistic example)', function () {
// Appears in the history
// TX #0CBB429C456ED999CC691DFCC8E62E8C8C7E9522C2BEA967FED0D7E2A9B28D13
// Note that XRP IOUs are no longer allowed, so this functionality is
// for historic transactions only.
var hex = '31585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C10000000000000000000000004254430000000000585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C131E4FE687C90257D3D2D694C8531CDEECBE84F33670000000000000000000000004254430000000000E4FE687C90257D3D2D694C8531CDEECBE84F3367310A20B3C85F482532A9578DBB3950B85CA06594D100000000000000000000000042544300000000000A20B3C85F482532A9578DBB3950B85CA06594D13000000000000000000000000055534400000000000A20B3C85F482532A9578DBB3950B85CA06594D1FF31585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C10000000000000000000000004254430000000000585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C131E4FE687C90257D3D2D694C8531CDEECBE84F33670000000000000000000000004254430000000000E4FE687C90257D3D2D694C8531CDEECBE84F33673115036E2D3F5437A83E5AC3CAEE34FF2C21DEB618000000000000000000000000425443000000000015036E2D3F5437A83E5AC3CAEE34FF2C21DEB6183000000000000000000000000055534400000000000A20B3C85F482532A9578DBB3950B85CA06594D1FF31585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C10000000000000000000000004254430000000000585E1F3BD02A15D6185F8BB9B57CC60DEDDB37C13157180C769B66D942EE69E6DCC940CA48D82337AD000000000000000000000000425443000000000057180C769B66D942EE69E6DCC940CA48D82337AD1000000000000000000000000058525000000000003000000000000000000000000055534400000000000A20B3C85F482532A9578DBB3950B85CA06594D100';
var json = [
[{
"account": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
"currency": "BTC",
"issuer": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K"
}, {
"account": "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
"currency": "BTC",
"issuer": "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo"
}, {
"account": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"currency": "BTC",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}, {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}],
[{
"account": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
"currency": "BTC",
"issuer": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K"
}, {
"account": "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
"currency": "BTC",
"issuer": "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo"
}, {
"account": "rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi",
"currency": "BTC",
"issuer": "rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi"
}, {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}],
[{
"account": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
"currency": "BTC",
"issuer": "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K"
}, {
"account": "r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn",
"currency": "BTC",
"issuer": "r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn"
}, {
"currency": "XRP",
"non_native": true
}, {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}]
];
var so = new SerializedObject();
types.PathSet.serialize(so, json);
assert.strictEqual(so.to_hex(), hex);
so = new SerializedObject(hex);
var parsed_path = SerializedObject.jsonify_structure(types.PathSet.parse(so));
assert.deepEqual(parsed_path, json);
});
it('Parse single empty path [[]]', function () {
var so = new SerializedObject('00');
var parsed_path = SerializedObject.jsonify_structure(types.PathSet.parse(so));
assert.deepEqual(parsed_path, [[]]);
});
it('Parse [[e],[e,e]]', function () {
var so = new SerializedObject('31000000000000000000000000000000000000007B00000000000000000000000055534400000000000000000000000000000000000000000000000315FF31000000000000000000000000000000000000007B000000000000000000000000425443000000000000000000000000000000000000000000000003153100000000000000000000000000000000000003DB0000000000000000000000004555520000000000000000000000000000000000000000000000014100');
var parsed_path = types.PathSet.parse(so);
var comp = [ [ { account: 'rrrrrrrrrrrrrrrrrrrrNxV3Xza',
currency: 'USD',
issuer: 'rrrrrrrrrrrrrrrrrrrpYnYCNYf' } ],
[ { account: 'rrrrrrrrrrrrrrrrrrrrNxV3Xza',
currency: 'BTC',
issuer: 'rrrrrrrrrrrrrrrrrrrpYnYCNYf' },
{ account: 'rrrrrrrrrrrrrrrrrrrpvQsW3V3',
currency: 'EUR',
issuer: 'rrrrrrrrrrrrrrrrrrrdHRtqg2' } ] ];
assert.deepEqual(SerializedObject.jsonify_structure(parsed_path, ""), comp);
});
});
describe('Object', function() {
it('Can parse objects with VL encoded Vector256', function() {
var hex = '110064220000000058000360186E008422E06B72D5B275E29EE3BE9D87A370F424E0E7BF613C4659098214289D19799C892637306AAAF03805EDFCDF6C28B8011320081342A0AB45459A54D8E4FA1842339A102680216CF9A152BCE4F4CE467D8246';
var so = new SerializedObject(hex);
var as_json = so.to_json();
var expected_json = {
"LedgerEntryType": "DirectoryNode",
"Owner": "rh6kN9s7spSb3vdv6H8ZGYzsddSLeEUGmc",
"Flags": 0,
"Indexes": [
"081342A0AB45459A54D8E4FA1842339A102680216CF9A152BCE4F4CE467D8246"
],
"RootIndex": "000360186E008422E06B72D5B275E29EE3BE9D87A370F424E0E7BF613C465909"
}
assert.deepEqual(as_json, expected_json);
assert.strictEqual(SerializedObject.from_json(expected_json).to_hex(), hex)
});
it('Serialize empty object {}', function () {
var so = new SerializedObject();
types.Object.serialize(so, {});
assert.strictEqual(so.to_hex(), 'E1');
});
it('Parse empty object {}', function () {
var so = new SerializedObject('E1');
var parsed_object = types.Object.parse(so)
assert.deepEqual(parsed_object, { });
});
it('Serialize simple object {TakerPays:"87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", TakerGets:213, Fee:"789"}', function () {
var so = new SerializedObject();
types.Object.serialize(so, {
TakerPays: '87654321.12345678/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
TakerGets: '213',
Fee: 789
});
assert.strictEqual(so.to_hex(), '64D65F241D335BF24E0000000000000000000000004555520000000000B5F762798A53D543A014CAF8B297CFF8F2F937E86540000000000000D5684000000000000315E1');
//TODO: Check independently.
});
it('Parse same object', function () {
var so = new SerializedObject('64D65F241D335BF24E0000000000000000000000004555520000000000B5F762798A53D543A014CAF8B297CFF8F2F937E86540000000000000D5684000000000000315E1');
var parsed_object=types.Object.parse(so);
var comp = { TakerPays:
{ value: '87654321.12345678',
currency: 'EUR',
issuer: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' },
TakerGets: '213',
Fee: '789' };
assert.deepEqual(SerializedObject.jsonify_structure(parsed_object, ""), comp);
//TODO: Check independently.
});
it('Serialize simple object {DestinationTag:123, QualityIn:456, QualityOut:789}', function () {
var so = new SerializedObject();
types.Object.serialize(so, {DestinationTag:123, QualityIn:456, QualityOut:789});
assert.strictEqual(so.to_hex(), '2E0000007B2014000001C8201500000315E1');
//TODO: Check independently.
});
it('Parse simple object {DestinationTag:123, QualityIn:456, QualityOut:789}', function () { //2E0000007B22000001C82400000315E1 2E0000007B2002000001C8200200000315E1
var so = new SerializedObject('2E0000007B2014000001C8201500000315E1');
var parsed_object=types.Object.parse(so);
assert.deepEqual(parsed_object, { DestinationTag:123, QualityIn:456, QualityOut:789 });
//TODO: Check independently.
});
});
describe('Array', function() {
it('Serialize empty array []', function () {
var so = new SerializedObject();
types.Array.serialize(so, []);
assert.strictEqual(so.to_hex(), 'F1');
});
it('Parse empty array []', function () {
var so = new SerializedObject('F1');
var parsed_object=types.Array.parse(so);
assert.deepEqual(parsed_object, []);
});
it('Serialize 3-length array [{TakerPays:123}); {TakerGets:456}, {Fee:789}]', function () {
var so = new SerializedObject();
types.Array.serialize(so, [{TakerPays:123}, {TakerGets:456}, {Fee:789}]);
//TODO: Check this manually
assert.strictEqual(so.to_hex(), '64400000000000007B6540000000000001C8684000000000000315F1');
});
it('Parse the same array', function () {
var so = new SerializedObject('64400000000000007B6540000000000001C8684000000000000315F1');
var parsed_object=types.Array.parse(so);
var comp = [ { TakerPays: '123' }, { TakerGets: '456' }, { Fee: '789' } ];
assert.deepEqual(SerializedObject.jsonify_structure(parsed_object, ""), comp);
});
it('Serialize 3-length array [{DestinationTag:123}); {QualityIn:456}, {Fee:789}]', function () {
var so = new SerializedObject();
types.Array.serialize(so, [{DestinationTag:123}, {QualityIn:456}, {Fee:789}]);
//TODO: Check this manually
assert.strictEqual(so.to_hex(), '2E0000007B2014000001C8684000000000000315F1');
});
it('Parse the same array 2', function () {
var so = new SerializedObject('2E0000007B2014000001C8684000000000000315F1');
var parsed_object = types.Array.parse(so);
var comp = [ { DestinationTag: 123 }, { QualityIn: 456 }, { Fee: '789' } ];
//TODO: Is this correct? Return some things as integers, and others as objects?
assert.deepEqual( SerializedObject.jsonify_structure(parsed_object, ""), comp);
});
});
});
// vim:sw=2:sts=2:ts=8:et

888
test/server-test.js Normal file
View File

@@ -0,0 +1,888 @@
var assert = require('assert');
var ws = require('ws');
var utils = require('./testutils');
var Remote = utils.load_module('remote').Remote;
var Server = utils.load_module('server').Server;
var Request = utils.load_module('request').Request;
var Transaction = utils.load_module('transaction').Transaction;
describe('Server', function() {
it('Server constructor - invalid options', function() {
assert.throws(function() {
var server = new Server(new Remote());
});
});
it('Message listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._handleMessage = function(message) {
assert.strictEqual(typeof message, 'string');
assert.deepEqual(JSON.parse(message).result, {});
done();
};
server.emit('message', JSON.stringify({result: {}}));
});
it('Subscribe response listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._handleResponseSubscribe = function(message) {
assert.strictEqual(typeof message, 'string');
assert.deepEqual(JSON.parse(message).result, {});
done();
};
server.emit('response_subscribe', JSON.stringify({result: {}}));
});
it('Activity listener', function(done) {
// Activity listener should be enabled
var server = new Server(new Remote(), 'wss://localhost:5006');
server.emit('ledger_closed');
var interval = setInterval(function(){}, Infinity);
assert.deepEqual(server._activityInterval.__proto__, interval.__proto__);
clearInterval(interval);
done();
});
it('Reconnect activity listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server.emit('ledger_closed');
var interval = setInterval(function(){}, Infinity);
assert.deepEqual(server._activityInterval.__proto__, interval.__proto__);
server.once('disconnect', function() {
// Interval should clear
assert.deepEqual(server._activityInterval.__proto__, interval.__proto__);
assert.strictEqual(server._activityInterval._onTimeout, null)
server.once('ledger_closed', function() {
// Interval should be reset
assert.deepEqual(server._activityInterval.__proto__, interval.__proto__);
assert.strictEqual(typeof server._activityInterval._onTimeout, 'function');
done();
});
server.emit('ledger_closed');
});
server.emit('disconnect');
});
it('Update server score ledger close listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
var ledger = {
'type': 'ledgerClosed',
'fee_base': 10,
'fee_ref': 10,
'ledger_hash': 'D29E1F2A2617A88E9DAA14F468B169E6875092ECA0B3B1FA2BE1BC5524DE7CB2',
'ledger_index': 7035609,
'ledger_time': 455327690,
'reserve_base': 20000000,
'reserve_inc': 5000000,
'txn_count': 1,
'validated_ledgers': '32570-7035609'
};
server._updateScore = function(type, data) {
assert.strictEqual(type, 'ledgerclose');
assert.deepEqual(data, ledger);
done();
};
server._remote.emit('ledger_closed', ledger);
});
it('Update server score ping listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
var ping = {
time: 500
};
server._updateScore = function(type, data) {
assert.strictEqual(type, 'response');
assert.deepEqual(data, ping);
done();
};
server.emit('response_ping', {}, ping);
});
it('Update server score load listener', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
var load = {
'fee_base': 10,
'fee_ref': 10
};
server._updateScore = function(type, data) {
assert.strictEqual(type, 'loadchange');
assert.deepEqual(data, load);
done();
};
server.emit('load_changed', load);
});
it('Websocket constructor', function() {
assert.strictEqual(Server.websocketConstructor(), require('ws'));
});
it('Set state online', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._state = 'offline';
server.once('connect', function() {
assert(server._connected);
done();
});
server._setState('online');
});
it('Set state offline', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._state = 'online';
server.once('disconnect', function() {
assert(!server._connected);
done();
});
server._setState('offline');
});
it('Set state same state', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._state = 'online';
server.once('state', function(state) {
assert(!server._connected);
assert.strictEqual(state, 'offline');
done();
});
server._setState('online');
server._setState('offline');
});
it('Check activity - inactive', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
server.reconnect = function() {
done();
};
server._lastLedgerClose = Date.now() - 1000 * 30;
server._checkActivity();
});
it('Check activity - unconnected', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = false;
server.reconnect = function() {
assert(false, 'Should not reconnect');
};
server._lastLedgerClose = Date.now() - 1000 * 30;
server._checkActivity();
setImmediate(function() {
done();
});
});
it('Check activity - uninitialized', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = false;
server.reconnect = function() {
assert(false, 'Should not reconnect');
};
//server._lastLedgerClose = Date.now() - 1000 * 30;
server._checkActivity();
setImmediate(function() {
done();
});
});
it('Check activity - sufficient ledger close', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = false;
server.reconnect = function() {
assert(false, 'Should not reconnect');
};
server._lastLedgerClose = Date.now() - 1000 * 20;
server._checkActivity();
setImmediate(function() {
done();
});
});
it('Update score - response', function() {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
assert.deepEqual(server._scoreWeights, {
ledgerclose: 5,
response: 1
});
assert.strictEqual(server._score, 0);
server._updateScore('response', { time: Date.now() - 1000 });
// 1000ms second ping / 200ms * weight of 1
assert.strictEqual(server._score, 5);
});
it('Update score - ledger', function() {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
server._lastLedgerIndex = 1;
assert.deepEqual(server._scoreWeights, {
ledgerclose: 5,
response: 1
});
assert.strictEqual(server._score, 0);
server._updateScore('ledgerclose', { ledger_index: 5 });
// Four ledgers behind the leading ledger * weight of 5
assert.strictEqual(server._score, 20);
});
it('Update score - load', function() {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
server._fee_cushion = 1;
assert.deepEqual(server._scoreWeights, {
ledgerclose: 5,
response: 1
});
assert.strictEqual(server._fee, 10);
server.emit('message', {
type: 'serverStatus',
load_base: 256 * 1,
load_factor: 256 * 10,
server_status: 'full'
});
//server._updateScore('loadchange', { });
assert.strictEqual(server._fee, 100);
});
it('Update score - reaching reconnect threshold', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._lastLedgerIndex = 1;
server._connected = true;
server.reconnect = function() {
done();
};
assert.deepEqual(server._scoreWeights, {
ledgerclose: 5,
response: 1
});
assert.strictEqual(server._score, 0);
server._updateScore('ledgerclose', { ledger_index: 250 });
// Four ledgers behind the leading ledger * weight of 5
assert.strictEqual(server._score, 1245);
});
it('Get remote address', function() {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
server._ws = {
_socket: {
remoteAddress: '127.0.0.1'
}
};
assert.strictEqual(server._remoteAddress(), '127.0.0.1');
});
it('Disconnect', function(done) {
var server = new Server(new Remote(), 'wss://localhost:5006');
server._connected = true;
server._ws = {
close: function() {
assert(!server._shouldConnect);
assert.strictEqual(server._state, 'offline');
done();
}
};
server.disconnect();
});
it('Connect', function(done) {
var wss = new ws.Server({ port: 5748 });
wss.once('connection', function(ws) {
ws.once('message', function(message) {
var m = JSON.parse(message);
assert.deepEqual(m, {
command: 'subscribe',
id: 0,
streams: [ 'ledger', 'server' ]
});
ws.send(JSON.stringify({
'id': 0,
'status': 'success',
'type': 'response',
'result': {
'fee_base': 10,
'fee_ref': 10,
'ledger_hash': '1838539EE12463C36F2C53B079D807C697E3D93A1936B717E565A4A912E11776',
'ledger_index': 7053695,
'ledger_time': 455414390,
'load_base': 256,
'load_factor': 256,
'random': 'E56C9154D9BE94D49C581179356C2E084E16D18D74E8B09093F2D61207625E6A',
'reserve_base': 20000000,
'reserve_inc': 5000000,
'server_status': 'full',
'validated_ledgers': '32570-7053695'
}
}));
wss.close();
});
});
var server = new Server(new Remote(), 'ws://localhost:5748');
server.once('connect', function() {
server.once('disconnect', function() {
done();
});
server.disconnect();
});
server.connect();
});
it('Connect - already connected', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = true;
server.once('connect', function() {
assert(false, 'Should not connect');
});
server.connect();
setImmediate(function() {
done();
});
});
it('Connect - prior WebSocket connection exists', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = false;
server._ws = {
close: function() {
done();
}
};
server.connect();
});
it('Connect - no WebSocket constructor', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = false;
var websocketConstructor = Server.websocketConstructor;
Server.websocketConstructor = function() {
return void(0);
};
assert.throws(function() {
server.connect();
}, Error);
Server.websocketConstructor = websocketConstructor;
});
it('Reconnect', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = true;
server._ws = { };
var disconnected = false;
server.disconnect = function() {
disconnected = true;
server.emit('disconnect');
};
server.connect = function() {
assert(disconnected);
done();
};
server.reconnect();
});
it('Retry connect', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = false;
server._shouldConnect = true;
server.connect = function() {
done();
};
server._retryConnect();
var timeout = setTimeout(function(){}, Infinity);
assert.deepEqual(server._retryTimer.__proto__, timeout.__proto__);
clearTimeout(timeout);
});
it('Handle close', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._ws = { };
server._handleClose();
var noOp = (function noOp(){}).toString();
var coverageRE = /__cov_.+;/;
assert.strictEqual(server._ws.onopen.toString().replace(coverageRE, ''), noOp);
assert.strictEqual(server._ws.onclose.toString().replace(coverageRE, ''), noOp);
assert.strictEqual(server._ws.onmessage.toString().replace(coverageRE, ''), noOp);
assert.strictEqual(server._ws.onerror.toString().replace(coverageRE, ''), noOp);
assert.strictEqual(server._state, 'offline');
});
it('Handle error', function(done) {
var wss = new ws.Server({ port: 5748 });
wss.once('connection', function(ws) {
ws.once('message', function(message) {
var m = JSON.parse(message);
assert.deepEqual(m, {
command: 'subscribe',
id: 0,
streams: [ 'ledger', 'server' ]
});
ws.send(JSON.stringify({
'id': 0,
'status': 'success',
'type': 'response',
'result': {
'fee_base': 10,
'fee_ref': 10,
'ledger_hash': '1838539EE12463C36F2C53B079D807C697E3D93A1936B717E565A4A912E11776',
'ledger_index': 7053695,
'ledger_time': 455414390,
'load_base': 256,
'load_factor': 256,
'random': 'E56C9154D9BE94D49C581179356C2E084E16D18D74E8B09093F2D61207625E6A',
'reserve_base': 20000000,
'reserve_inc': 5000000,
'server_status': 'full',
'validated_ledgers': '32570-7053695'
}
}));
});
});
var server = new Server(new Remote(), 'ws://localhost:5748');
server.once('connect', function() {
server._retryConnect = function(){
wss.close();
done();
};
server._ws.emit('error', new Error());
});
server.connect();
});
it('Handle message - ledgerClosed', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
var ledger = {
type: 'ledgerClosed',
ledger_index: 1
};
server.once('ledger_closed', function(message) {
assert.strictEqual(server._lastLedgerIndex, ledger.ledger_index);
done();
});
server.emit('message', ledger);
});
it('Handle message - serverStatus', function(done) {
var remote = new Remote();
var server = new Server(remote, 'ws://localhost:5748');
var events = 3;
var receivedEvents = 0;
var status = {
type: 'serverStatus',
load_base: 256,
load_factor: 256 * 2
};
server.once('load', function(message) {
assert.deepEqual(message, status);
if (++receivedEvents == events) {
done();
}
});
server.once('load_changed', function(message) {
assert.deepEqual(message, status);
if (++receivedEvents == events) {
done();
}
});
remote.once('load_changed', function(message) {
assert.deepEqual(message, status);
if (++receivedEvents == events) {
done();
}
});
server.emit('message', status);
});
it('Handle message - serverStatus - no load', function(done) {
var remote = new Remote();
var server = new Server(remote, 'ws://localhost:5748');
var events = 3;
var receivedEvents = 0;
var status = {
type: 'serverStatus'
};
server.once('load', function(message) {
assert.deepEqual(message, status);
});
server.once('load_changed', function(message) {
assert(false, 'Non-load status should not trigger events');
});
remote.once('load_changed', function(message) {
assert(false, 'Non-load status should not trigger events');
});
server.emit('message', status);
setImmediate(function() {
done();
});
});
it('Handle message - response - success', function(done) {
var remote = new Remote();
var server = new Server(remote, 'ws://localhost:5748');
var request = new Request(remote, 'server_info');
var id = 1;
assert(request instanceof process.EventEmitter);
server._requests[id] = request;
var response = {
id: id,
type: 'response',
status: 'success',
result: {
test: 'property'
}
};
var receivedEvents = 0;
var emitters = 3;
request.once('success', function(message) {
assert.deepEqual(message, response.result);
if (++receivedEvents === emitters) {
done();
}
});
server.once('response_server_info', function(message) {
assert.deepEqual(message, response.result);
if (++receivedEvents === emitters) {
done();
}
});
remote.once('response_server_info', function(message) {
assert.deepEqual(message, response.result);
if (++receivedEvents === emitters) {
done();
}
});
server.emit('message', response);
});
it('Handle message - response - error', function(done) {
var remote = new Remote();
var server = new Server(remote, 'ws://localhost:5748');
var request = new Request(remote, 'server_info');
var id = 1;
assert(request instanceof process.EventEmitter);
server._requests[id] = request;
var response = {
id: id,
type: 'response',
status: 'error',
error: {
test: 'property'
}
};
var receivedEvents = 0;
request.once('error', function(message) {
assert.deepEqual(message, {
error: 'remoteError',
error_message: 'Remote reported an error.',
remote: response
});
done();
});
server.emit('message', response);
});
it('Handle message - response - no request', function(done) {
var remote = new Remote();
var server = new Server(remote, 'ws://localhost:5748');
var response = {
id: 1,
type: 'response',
status: 'success',
result: { }
};
Object.defineProperty(response, 'status', {
get: function() {
assert(false, 'Response status should not be checked');
}
});
server.emit('message', response);
setImmediate(function() {
done();
});
});
it('Handle message - path_find', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._handlePathFind = function() {
done();
};
server.emit('message', { type: 'path_find' });
});
it('Handle message - invalid message', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server.once('unexpected', function() {
done();
});
server.emit('message', { butt: 'path_find' });
});
it('Send message', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
var request = {
id: 1,
message: {
command: 'server_info'
}
};
server._ws = {
send: function(message) {
assert.deepEqual(JSON.parse(message), request);
done();
}
};
server._sendMessage(request);
});
it('Request', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = true;
server._ws = { };
var request = {
message: {
command: 'server_info'
}
};
server._sendMessage = function(message) {
done();
};
server._request(request);
});
it('Request - delayed connect', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = false;
server._ws = { };
var request = {
message: {
command: 'server_info'
}
};
server._request(request);
setImmediate(function() {
server._sendMessage = function(message) {
done();
};
server.emit('connect');
});
});
it('Request - no WebSocket', function(done) {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = true;
server._ws = void(0);
var request = {
message: {
command: 'server_info'
}
};
server._sendMessage = function(message) {
assert(false, 'Should not send message if WebSocket does not exist');
};
server._request(request);
setImmediate(function() {
done();
});
});
it('Check connectivity', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._connected = false;
server._ws = { readyState: 1 };
assert(!server._isConnected());
assert(!server._isConnected({ message: { command: 'ping' } }));
assert(server._isConnected({ message: { command: 'subscribe' } }));
server._connected = true;
assert(server._isConnected());
});
it('Compute fee - transaction', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
var transaction = new Transaction();
assert.strictEqual(server._computeFee(transaction), '12');
});
it('Compute fee - fee units', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
var transaction = new Transaction();
assert.strictEqual(server._computeFee(10), '12');
});
it('Compute fee - bad arg', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
var transaction = new Transaction();
assert.throws(function() {
server._computeFee('asdf');
});
});
it('Compute fee - increased load', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._load_base = 256;
server._load_factor = 256 * 4;
var transaction = new Transaction();
assert.strictEqual(server._computeFee(transaction), '48');
});
it('Compute reserve', function() {
var server = new Server(new Remote(), 'ws://localhost:5748');
server._reserve_base = 20000000;
server._reserve_inc = 5000000;
assert.strictEqual(server._reserve().to_json(), '20000000');
});
});

View File

@@ -1,30 +1,56 @@
var buster = require("buster");
var assert = require('assert');
var utils = require('./testutils');
var Seed = utils.load_module('seed').Seed;
var Seed = require("../src/js/ripple/seed").Seed;
try {
var conf = require('./config');
} catch(exception) {
var conf = require('./config-example');
function _isNaN(n) {
return typeof n === 'number' && isNaN(n);
}
var config = require('../src/js/ripple/config').load(conf);
buster.testCase("Signing", {
"Keys" : {
"SigningPubKey 1 (ripple-client issue #245)" : function () {
var seed = Seed.from_json("saESc82Vun7Ta5EJRzGJbrXb5HNYk");
var key = seed.get_key("rBZ4j6MsoctipM6GEyHSjQKzXG3yambDnZ");
describe('Signing', function() {
describe('Keys', function() {
it('SigningPubKey 1 (ripple-client issue #245)', function () {
var seed = Seed.from_json('saESc82Vun7Ta5EJRzGJbrXb5HNYk');
var key = seed.get_key('rBZ4j6MsoctipM6GEyHSjQKzXG3yambDnZ');
var pub = key.to_hex_pub();
buster.assert.equals(pub, "0396941B22791A448E5877A44CE98434DB217D6FB97D63F0DAD23BE49ED45173C9");
},
"SigningPubKey 2 (master seed)" : function () {
var seed = Seed.from_json("snoPBrXtMeMyMHUVTgbuqAfg1SUTb");
var key = seed.get_key("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh");
assert.strictEqual(pub, '0396941B22791A448E5877A44CE98434DB217D6FB97D63F0DAD23BE49ED45173C9');
});
it('SigningPubKey 2 (master seed)', function () {
var seed = Seed.from_json('snoPBrXtMeMyMHUVTgbuqAfg1SUTb');
var key = seed.get_key('rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh');
var pub = key.to_hex_pub();
buster.assert.equals(pub, "0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020");
}
}
assert.strictEqual(pub, '0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020');
});
});
describe('parse_json', function() {
it('empty string', function() {
assert(_isNaN(new Seed().parse_json('').to_json()));
});
it('hex string', function() {
var str = new Array(33).join('0');
assert(_isNaN(new Seed().parse_json(str).to_json()));
});
it('passphrase', function() {
var str = new Array(60).join('0');
assert.strictEqual('snFRPnVL3secohdpwSie8ANXdFQvG', new Seed().parse_json(str).to_json());
});
it('null', function() {
assert(_isNaN(new Seed().parse_json(null).to_json()));
});
});
describe('parse_passphrase', function() {
it('invalid passphrase', function() {
assert.throws(function() {
new Seed().parse_passphrase(null);
});
});
});
describe('get_key', function() {
it('get key from invalid seed', function() {
assert.throws(function() {
new Seed().get_key('rBZ4j6MsoctipM6GEyHSjQKzXG3yambDnZ');
});
});
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -0,0 +1,28 @@
var assert = require('assert');
var utils = require('./testutils');
var sjcl = require('../build/sjcl');
var Seed = require('../src/js/ripple/seed').Seed;
describe('SJCL ECDSA Canonicalization', function() {
describe('canonicalizeSignature', function() {
it('should canonicalize non-canonical signatures', function () {
var seed = Seed.from_json('saESc82Vun7Ta5EJRzGJbrXb5HNYk');
var key = seed.get_key('rBZ4j6MsoctipM6GEyHSjQKzXG3yambDnZ');
var rs = sjcl.codec.hex.toBits("27ce1b914045ba7e8c11a2f2882cb6e07a19d4017513f12e3e363d71dc3fff0fb0a0747ecc7b4ca46e45b3b32b6b2a066aa0249c027ef11e5bce93dab756549c");
rs = sjcl.ecc.ecdsa.secretKey.prototype.canonicalizeSignature.call(key._secret, rs);
assert.strictEqual(sjcl.codec.hex.fromBits(rs), "27ce1b914045ba7e8c11a2f2882cb6e07a19d4017513f12e3e363d71dc3fff0f4f5f8b813384b35b91ba4c4cd494d5f8500eb84aacc9af1d6403cab218dfeca5");
});
it('should not touch canonical signatures', function () {
var seed = Seed.from_json('saESc82Vun7Ta5EJRzGJbrXb5HNYk');
var key = seed.get_key('rBZ4j6MsoctipM6GEyHSjQKzXG3yambDnZ');
var rs = sjcl.codec.hex.toBits("5c32bc2b4d34e27af9fb66eeea0f47f6afb3d433658af0f649ebae7b872471ab7d23860688aaf9d8131f84cfffa6c56bf9c32fd8b315b2ef9d6bcb243f7a686c");
rs = sjcl.ecc.ecdsa.secretKey.prototype.canonicalizeSignature.call(key._secret, rs);
assert.strictEqual(sjcl.codec.hex.fromBits(rs), "5c32bc2b4d34e27af9fb66eeea0f47f6afb3d433658af0f649ebae7b872471ab7d23860688aaf9d8131f84cfffa6c56bf9c32fd8b315b2ef9d6bcb243f7a686c");
});
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -0,0 +1,245 @@
var assert = require('assert');
var utils = require('./testutils');
var sjcl = require('../build/sjcl');
describe('ECDSA signing with recoverable public key', function(){
describe('Sign and recover public key from signature', function(){
it('should recover public keys from signatures it generates', function(){
var messages = [{
message: 'Hello world!',
secret_hex: '9931c08f61f127d5735fa3c60e702212ce7ed9a2ac90d5dbade99c689728cd9b',
random_value: '5473a3dbdc13ec9efbad7f7f929fbbea404af556a48041dd9d41d29fdbc989ad',
hash_function: sjcl.hash.sha512.hash
// signature: 'AAAAGzFa1pYjhssCpDFZgFSnYQ8qCnMkLaZrg0mXZyNQ2NxgMQ8z9U3ngYerxSZCEt3Q4raMIpt03db7jDNGbfmHy8I='
}, {
// Correct recovery value for this one is 0
message: 'ua5pdcG0I1JuhSr9Fwai2UoZ9ll5leUtHE5NzSSNnPkw8nSPH5mT1gE1fe0sn',
secret_hex: '84814318ffe6e612694ad59b9084b7b66d68b6979567c619171a67b05e2b654b',
random_value: '14261d30b319709c10ab13cabe595313b99dd2d5c76b8b38d7eb445f0b81cc9a',
hash_function: sjcl.hash.sha512.hash
// signature: 'AAAAHGjpBM7wnTHbPGo0TXsxKbr+d7KvACuJ/eGQsp3ZJfOOQHszaciRo3ClenwKixcquFcBlaVfHlOc3JWOZq1RjpQ='
}, {
// Correct recovery value for this one is 1
message: 'rxc76UnmVTp',
secret_hex: '37eac47c212be8ea8372f506b11673c281cd9ea29a035c2c9e90d027c3dbecc6',
random_value: '61b53ca6de0543f911765ae216a3a4d851918a0733fba9ac80cf29de5bec8032',
hash_function: sjcl.hash.sha256.hash
// signature: 'AAAAG8L/yOA3nNqK4aOiQWJmOaWvkvr3NoTk6wCdX97U3qowdgFd98UK3evWV16qO3RHgFMEnUW/Vt4+kcidqW6hMo0='
}];
var curve = sjcl.ecc.curves['c256'];
for (var m = 0; m < messages.length; m++) {
var message = messages[m].message;
var secret_hex = messages[m].secret_hex;
var random_value = messages[m].random_value;
var hash_function = messages[m].hash_function;
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var pub_val_point = secret_key._curve.G.mult(secret_key._exponent);
var public_key = new sjcl.ecc.ecdsa.publicKey(curve, pub_val_point);
var hash = hash_function(message);
var recoverable_signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
var recovered_public_key = sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, recoverable_signature);
assert.deepEqual(public_key.get().x, recovered_public_key.get().x, 'The x value for the recovered public key did not match for message: ' + message + '. Expected: ' + public_key.get().x.toString() + '. Actual: ' + recovered_public_key.get().x.toString());
assert.deepEqual(public_key.get().y, recovered_public_key.get().y, 'The y value for the recovered public key did not match for message: ' + message + '. Expected: ' + public_key.get().y.toString() + '. Actual: ' + recovered_public_key.get().y.toString());
}
});
});
describe('signWithRecoverablePublicKey', function(){
// it('should produce the same values as bitcoinjs-lib\'s implementation', function(){
// // TODO: figure out why bitcoinjs-lib and this produce different signature values
// var curve = sjcl.ecc.curves['c256'];
// var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
// var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
// var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
// // var public_key = '0217b9f5b3ba8d550f19fdfb5233818cd27d19aaea029b667f547f5918c307ed3b';
// var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
// var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
// var bitcoin_signature_base64 = 'IJPzXewhO1CORRx14FROzZC8ne4v0Me94UZoBKH15e4pcSgeYiYeKZ4PJOBI/D5yqUOhemO+rKKHhE0HL66kAcM=';
// var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
// var signature_base64 = sjcl.codec.base64.fromBits(signature);
// assert.equal(signature_base64, bitcoin_signature_base64);
// });
it('should produce an error if the hash is not given as a bitArray', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = 'e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778';
assert.throws(function(){
secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
}, /(?=.*hash)(?=.*bitArray).+/);
});
it('should return a bitArray', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
assert(typeof signature === 'object' && signature.length > 0 && typeof signature[0] === 'number');
});
it('should return a bitArray where the first word contains the recovery factor', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
var recovery_factor = signature[0] - 27;
assert(recovery_factor >= 0 && recovery_factor < 4);
});
});
describe('recoverFromSignature', function(){
// it('should be able to recover public keys from bitcoinjs-lib\'s implementation', function(){
// // TODO: figure out why bitcoinjs-lib and this produce different signature values
// var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
// var signature = sjcl.codec.base64.toBits('IJPzXewhO1CORRx14FROzZC8ne4v0Me94UZoBKH15e4pcSgeYiYeKZ4PJOBI/D5yqUOhemO+rKKHhE0HL66kAcM=');
// var public_key = sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
// });
it('should produce an error if the signature given does not have the recovery factor prefix', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.sign(hash, 0, random_value);
assert.throws(function(){
sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
}, /(?=.*signature)(?=.*recovery factor)(?=.*public key).*/);
});
it('should produce an error if it is not given both the hash and the signature', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
assert.throws(function(){
sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash);
}, /(?=.*hash\ and\ signature)(?=.*recover\ public\ key).*/);
assert.throws(function(){
sjcl.ecc.ecdsa.publicKey.recoverFromSignature(signature);
}, /(?=.*hash\ and\ signature)(?=.*recover\ public\ key).*/);
});
it('should produce an error if it cannot generate a valid public key from the the signature', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = sjcl.codec.base64.toBits('IJPzXewhO1CORRx14FROzZC8ne4v0Me94UZoBKH15e4pcSgeYiYeKZ4PJOBI/D5yqUOhemO+rKKHhE0HL66kAcM=');
signature[0] = 27;
signature[3] = 0 - signature[3];
assert.throws(function(){
sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
}, /(?=.*Cannot\ recover\ public\ key).*/);
});
it('should return a publicKey object', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
var key = sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
assert(key instanceof sjcl.ecc.ecdsa.publicKey);
});
it('tampering with the signature should produce a different public key, if it produces a valid one at all', function(){
var curve = sjcl.ecc.curves['c256'];
var secret_hex = '9e623166ac44d4e75fa842f3443485b9c8380551132a8ffaa898b5c93bb18b7d';
var secret_bn = sjcl.bn.fromBits(sjcl.codec.hex.toBits(secret_hex));
var secret_key = new sjcl.ecc.ecdsa.secretKey(curve, secret_bn);
var random_value = 'c3aa71cecb965bbbc96083d868b4955d77adb4e02ce229fe60869f745dfcd4e4a4d0f17a15a353d7592dca1baba2824e45c8e7a8f9faad3ce2c2d3792799f27a';
var hash = sjcl.codec.hex.toBits('e865bcc63a86ef21585ac8340a7cc8590ed85175a2a718c6fb2bfb2715d13778');
var signature = secret_key.signWithRecoverablePublicKey(hash, 0, random_value);
signature[3]++;
var original_public_key = new sjcl.ecc.ecdsa.publicKey(curve, curve.G.mult(secret_key._exponent));
var recovered_public_key = sjcl.ecc.ecdsa.publicKey.recoverFromSignature(hash, signature);
assert.notDeepEqual(original_public_key.get().x, recovered_public_key.get().x);
assert.notDeepEqual(original_public_key.get().y, recovered_public_key.get().y);
});
});
});

View File

@@ -0,0 +1,52 @@
var assert = require('assert');
var utils = require('./testutils');
var sjcl = require('../build/sjcl');
describe('SJCL Extramath', function() {
describe('setBitM', function() {
it('0x0f set bit 4 => 0x1f', function () {
var val = new sjcl.bn("0f");
val.setBitM(4);
assert.strictEqual(val.toString(), '0x1f');
});
it('0x0f set bit 23 => 0x80000f', function () {
var val = new sjcl.bn("0f");
val.setBitM(23);
assert.strictEqual(val.toString(), '0x80000f');
});
it('0x0f set bit 24 => 0x100000f', function () {
var val = new sjcl.bn("0f");
val.setBitM(24);
assert.strictEqual(val.toString(), '0x100000f');
});
});
describe('testBit', function() {
it('0x03', function () {
var val = new sjcl.bn("03");
assert.strictEqual(val.testBit(0), 1);
assert.strictEqual(val.testBit(1), 1);
assert.strictEqual(val.testBit(2), 0);
});
it('0x1000000', function () {
var val = new sjcl.bn("1000000");
assert.strictEqual(val.testBit(25), 0);
assert.strictEqual(val.testBit(24), 1);
assert.strictEqual(val.testBit(23), 0);
assert.strictEqual(val.testBit( 1), 0);
assert.strictEqual(val.testBit( 0), 0);
});
it('0xff7fffffff', function () {
var val = new sjcl.bn("ff7fffffff");
assert.strictEqual(val.testBit(32), 1);
assert.strictEqual(val.testBit(31), 0);
assert.strictEqual(val.testBit(30), 1);
assert.strictEqual(val.testBit(24), 1);
assert.strictEqual(val.testBit(23), 1);
assert.strictEqual(val.testBit(22), 1);
assert.strictEqual(val.testBit( 1), 1);
assert.strictEqual(val.testBit( 0), 1);
});
});
});
// vim:sw=2:sts=2:ts=8:et

48
test/sjcl-jacobi-test.js Normal file
View File

@@ -0,0 +1,48 @@
var assert = require('assert');
var utils = require('./testutils');
var sjcl = require('../build/sjcl');
describe('SJCL Jacobi', function() {
it('(15/13) = -1', function () {
var jac = new sjcl.bn(15).jacobi(13);
assert.strictEqual(jac, -1);
});
it('(4/97) = 1', function () {
var jac = new sjcl.bn(4).jacobi(97);
assert.strictEqual(jac, 1);
});
it('(17/17) = 0', function () {
var jac = new sjcl.bn(17).jacobi(17);
assert.strictEqual(jac, 0);
});
it('(34/17) = 0', function () {
var jac = new sjcl.bn(34).jacobi(17);
assert.strictEqual(jac, 0);
});
it('(19/45) = 1', function () {
var jac = new sjcl.bn(19).jacobi(45);
assert.strictEqual(jac, 1);
});
it('(8/21) = -1', function () {
var jac = new sjcl.bn(8).jacobi(21);
assert.strictEqual(jac, -1);
});
it('(5/21) = 1', function () {
var jac = new sjcl.bn(5).jacobi(21);
assert.strictEqual(jac, 1);
});
it('(1001/9907) = -1', function () {
var jac = new sjcl.bn(1001).jacobi(9907);
assert.strictEqual(jac, -1);
});
it('(1236/20003) = 1', function () {
var jac = new sjcl.bn(1236).jacobi(20003);
assert.strictEqual(jac, 1);
});
it('With huge numbers', function () {
var jac = new sjcl.bn("217033ffbc5a462201407027104916c5e7bf09f2b0c926f7c5cb20858be29d92e7fe67080eeb268fcbc2bc44d9cecfe1d3acbb302111eba355a8b769ed4bdbf773d37dca47e2293c173ff4f84b38f4e84bfad7cc1a913d70e11cf664a95575b80ec9d10123289b402ad2c71c70f2dc28360262d3d703faa964c741a711e4eebd324d659601dd14564fcd8c5908bbf8c97cf3ff82f083da3005848b48cb545b31be2039cca1d67714f32d32b3228c1a659415ee6c138ca274f789006a90a9a41bbc3934b84c78948eae8351f45696fa716b1328561f4c3bbb44ac73112c291b6b4587365e44fa09d583fb8074eb35bf947231e500c0d2c79c5fb957e50e84f6c9").jacobi("c7f1bc1dfb1be82d244aef01228c1409c198894eca9e21430f1669b4aa3864c9f37f3d51b2b4ba1ab9e80f59d267fda1521e88b05117993175e004543c6e3611242f24432ce8efa3b81f0ff660b4f91c5d52f2511a6f38181a7bf9abeef72db056508bbb4eeb5f65f161dd2d5b439655d2ae7081fcc62fdcb281520911d96700c85cdaf12e7d1f15b55ade867240722425198d4ce39019550c4c8a921fc231d3e94297688c2d77cd68ee8fdeda38b7f9a274701fef23b4eaa6c1a9c15b2d77f37634930386fc20ec291be95aed9956801e1c76601b09c413ad915ff03bfdc0b6b233686ae59e8caf11750b509ab4e57ee09202239baee3d6e392d1640185e1cd");
assert.strictEqual(jac, -1);
});
});
// vim:sw=2:sts=2:ts=8:et

88
test/sjcl-montgomery.js Normal file
View File

@@ -0,0 +1,88 @@
var assert = require('assert');
var utils = require('./testutils');
var sjcl = require('../build/sjcl');
function testExp(vec) {
var actual = new sjcl.bn(vec.g).powermodMontgomery(new sjcl.bn(vec.e),
new sjcl.bn(vec.m));
assert.strictEqual(actual.toString(), new sjcl.bn(vec.r).toString());
}
describe('SJCL Montgomery Exponentiation', function() {
describe('powermod', function() {
it('test 1', function () {
testExp({
g: 2,
e: 3,
m: 3,
r: 2
});
});
it('test 2', function () {
testExp({
g: 2,
e: "10000000000000000000000000",
m: 1337,
r: 1206
});
});
it('test 3', function () {
testExp({
g: 17,
e: 90,
m: 34717861147,
r: 28445204336
});
});
it('test 4', function () {
testExp({
g: 2,
e: "0x844A000000000000000000000",
m: 13,
r: 9
});
});
it('test 5', function () {
testExp({
g: 2,
e: 0x1010,
m: 131,
r: 59
});
});
it('test 6', function () {
testExp({
g: 2,
e: "43207437777777877617151",
m: 13,
r: 2
});
});
it('test 7', function () {
testExp({
g: 2,
e: "389274238947216444871600001871964319565192765874149",
m: 117,
r: 44
});
});
it('test 8', function () {
testExp({
g: 2,
e: "89457115510016156219817846189181057618965150496979174671534084187",
m: "1897166415676096761",
r: "16840615e646a4c5c8d"
});
});
it('test 9', function () {
testExp({
g: "4c3399bebab284bc7f9056efe17ea39db324ffa1d52dc1542eb16a749570789359f192535b7bcb514b36be9cdb4fb2a6ba3ad6b4248034e9a1d2a8612cd9d885242b4f679524121b74f79d7db14859fccde1c0dfe6ef002dcbc777ab5fcf4432",
e: "000322e6b6dafe138ccd6a991977d19",
m: "a5091daa41997943e3c98469e93377f668d05d8059bc53f72aaacdac3729a3070dc7439a5171160bf9ec2826b7191b03b0e84b28e14dd376de35d29a96f686666e053ab62a41ebc2b5f52e8cf06254100fd153a1cda4485f170c39c54689e52d",
r: "554336ea044782d29f091117cfeaeee2334b4242bd7428d0bba3ce5325781dc219e891e54698cb0193ffe7c6fc07f1808f6685e64b6a082815f6afd2e16c7a61316b5e3e59cd8b3984d5a76c8e173f8615f7dceac0c99e27e4abfb1278dfa67f"
});
});
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,484 +1,31 @@
var async = require("async");
var ripple = require('../src/js/ripple');
var Amount = require("../src/js/ripple/amount").Amount;
var Remote = require("../src/js/ripple/remote").Remote;
var Server = require("./server").Server;
exports.get_config = get_config;
var config = require('../src/js/ripple/config').load(require('./config'));
var account_dump = function (remote, account, callback) {
var self = this;
async.waterfall([
function (callback) {
self.what = "Get latest account_root";
remote
.request_ledger_entry('account_root')
.ledger_hash(remote.ledger_hash())
.account_root("root")
.on('success', function (r) {
//console.log("account_root: %s", JSON.stringify(r, undefined, 2));
callback();
})
.on('error', function(m) {
console.log("error: %s", m);
buster.assert(false);
callback();
})
.request();
},
], function (error) {
callback(error);
});
// get closed ledger hash
// get account root
// construct a json result
//
};
/**
* Helper called by test cases to generate a setUp routine.
*
* By default you would call this without options, but it is useful to
* be able to plug options in during development for quick and easy
* debugging.
*
* @example
* buster.testCase("Foobar", {
* setUp: testutils.build_setup({verbose: true}),
* // ...
* });
*
* @param opts {Object} These options allow quick-and-dirty test-specific
* customizations of your test environment.
* @param opts.verbose {Bool} Enable all debug output (then cover your ears
* and run)
* @param opts.verbose_ws {Bool} Enable tracing in the Remote class. Prints
* websocket traffic.
* @param opts.verbose_server {Bool} Set the -v option when running rippled.
* @param opts.no_server {Bool} Don't auto-run rippled.
* @param host {String} Identifier for the host configuration to be used.
*/
var build_setup = function (opts, host) {
opts = opts || {};
// Normalize options
if (opts.verbose) {
opts.verbose_ws = true;
opts.verbose_server = true;
};
return function (done) {
var self = this;
host = host || config.server_default;
this.store = this.store || {};
var data = this.store[host] = this.store[host] || {};
data.opts = opts;
async.series([
function runServerStep(callback) {
if (opts.no_server) return callback();
data.server = Server
.from_config(host, !!opts.verbose_server)
.on('started', callback)
.on('exited', function () {
// If know the remote, tell it server is gone.
if (self.remote)
self.remote.server_fatal();
})
.start();
},
function connectWebsocketStep(callback) {
self.remote = data.remote =
Remote
.from_config(host, !!opts.verbose_ws)
.once('ledger_closed', callback)
.connect();
}
], done);
};
};
/**
* Generate tearDown routine.
*
* @param host {String} Identifier for the host configuration to be used.
*/
var build_teardown = function (host) {
return function (done) {
host = host || config.server_default;
var data = this.store[host];
var opts = data.opts;
async.series([
function disconnectWebsocketStep(callback) {
data.remote
.on('disconnected', callback)
.connect(false);
},
function stopServerStep(callback) {
if (opts.no_server)
{
return callback();
}
data.server
.on('stopped', callback)
.stop();
}
], done);
};
};
var create_accounts = function (remote, src, amount, accounts, callback) {
assert(5 === arguments.length);
remote.set_account_seq(src, 1);
async.forEach(accounts, function (account, callback) {
// Cache the seq as 1.
// Otherwise, when other operations attempt to opperate async against the account they may get confused.
remote.set_account_seq(account, 1);
remote.transaction()
.payment(src, account, amount)
.on('proposed', function (m) {
// console.log("proposed: %s", JSON.stringify(m));
if (m.result != 'tesSUCCESS') {
callback(new Error("Transaction did not succeed."));
} else callback(null);
})
.on('error', function (m) {
// console.log("error: %s", JSON.stringify(m));
callback(m);
})
.submit();
}, callback);
};
var credit_limit = function (remote, src, amount, callback) {
assert(4 === arguments.length);
var _m = amount.match(/^(\d+\/...\/[^\:]+)(?::(\d+)(?:,(\d+))?)?$/);
if (!_m) {
console.log("credit_limit: parse error: %s", amount);
callback('parse_error');
function get_config() {
var config = { };
try {
config = require('./config');
} catch(exception) {
config = require('./config-example');
}
else
{
// console.log("credit_limit: parsed: %s", JSON.stringify(_m, undefined, 2));
var _account_limit = _m[1];
var _quality_in = _m[2];
var _quality_out = _m[3];
return load_config(config);
};
remote.transaction()
.ripple_line_set(src, _account_limit, _quality_in, _quality_out)
.on('proposed', function (m) {
// console.log("proposed: %s", JSON.stringify(m));
exports.load_config = load_config;
callback(m.result != 'tesSUCCESS');
})
.on('error', function (m) {
// console.log("error: %s", JSON.stringify(m));
function load_config(config) {
return load_module('config').load(config);
};
callback(m);
})
.submit();
exports.load_module = load_module;
function load_module(name) {
if (process.env.RIPPLE_LIB_COV) {
return require('../src-cov/js/ripple/' + name)
} else if (!ripple.hasOwnProperty(name)) {
return require('../src/js/ripple/' + name);
} else {
return require('../src/js/ripple')[name];
}
};
var verify_limit = function (remote, src, amount, callback) {
assert(4 === arguments.length);
var _m = amount.match(/^(\d+\/...\/[^\:]+)(?::(\d+)(?:,(\d+))?)?$/);
if (!_m) {
// console.log("credit_limit: parse error: %s", amount);
callback('parse_error');
}
else
{
// console.log("verify_limit: parsed: %s", JSON.stringify(_m, undefined, 2));
var _account_limit = _m[1];
var _quality_in = _m[2];
var _quality_out = _m[3];
var _limit = Amount.from_json(_account_limit);
remote.request_ripple_balance(src, _limit.issuer().to_json(), _limit.currency().to_json(), 'CURRENT')
.once('ripple_state', function (m) {
buster.assert(m.account_limit.equals(_limit));
buster.assert('undefined' === _quality_in || m.account_quality_in == _quality_in);
buster.assert('undefined' === _quality_out || m.account_quality_out == _quality_out);
callback();
})
.once('error', function (m) {
// console.log("error: %s", JSON.stringify(m));
callback(m);
})
.request();
}
};
var credit_limits = function (remote, balances, callback) {
assert(3 === arguments.length);
var limits = [];
for (var src in balances) {
var values_src = balances[src];
var values = 'string' === typeof values_src ? [ values_src ] : values_src;
for (var index in values) {
limits.push( { "source" : src, "amount" : values[index] } );
}
}
async.every(limits,
function (limit, callback) {
credit_limit(remote, limit.source, limit.amount,
function (mismatch) { callback(!mismatch); });
},
function (every) {
callback(!every);
});
};
var ledger_close = function (remote, callback) {
remote.once('ledger_closed', function (m) { callback(); }).ledger_accept();
}
var payment = function (remote, src, dst, amount, callback) {
assert(5 === arguments.length);
remote.transaction()
.payment(src, dst, amount)
.on('proposed', function (m) {
// console.log("proposed: %s", JSON.stringify(m));
callback(m.result != 'tesSUCCESS');
})
.on('error', function (m) {
// console.log("error: %s", JSON.stringify(m));
callback(m);
})
.submit();
};
var payments = function (remote, balances, callback) {
assert(3 === arguments.length);
var sends = [];
for (var src in balances) {
var values_src = balances[src];
var values = 'string' === typeof values_src ? [ values_src ] : values_src;
for (var index in values) {
var amount_json = values[index];
var amount = Amount.from_json(amount_json);
sends.push( { "source" : src, "destination" : amount.issuer().to_json(), "amount" : amount_json } );
}
}
async.every(sends,
function (send, callback) {
payment(remote, send.source, send.destination, send.amount,
function (mismatch) { callback(!mismatch); });
},
function (every) {
callback(!every);
});
};
var transfer_rate = function (remote, src, billionths, callback) {
assert(4 === arguments.length);
remote.transaction()
.account_set(src)
.transfer_rate(billionths)
.on('proposed', function (m) {
// console.log("proposed: %s", JSON.stringify(m));
callback(m.result != 'tesSUCCESS');
})
.on('error', function (m) {
// console.log("error: %s", JSON.stringify(m));
callback(m);
})
.submit();
};
var verify_balance = function (remote, src, amount_json, callback) {
assert(4 === arguments.length);
var amount_req = Amount.from_json(amount_json);
if (amount_req.is_native()) {
remote.request_account_balance(src, 'CURRENT')
.once('account_balance', function (amount_act) {
if (!amount_act.equals(amount_req, true)) {
console.log("verify_balance: failed: %s / %s",
amount_act.to_text_full(),
amount_req.to_text_full());
}
callback(!amount_act.equals(amount_req, true));
})
.request();
}
else {
remote.request_ripple_balance(src, amount_req.issuer().to_json(), amount_req.currency().to_json(), 'CURRENT')
.once('ripple_state', function (m) {
// console.log("BALANCE: %s", JSON.stringify(m));
// console.log("account_balance: %s", m.account_balance.to_text_full());
// console.log("account_limit: %s", m.account_limit.to_text_full());
// console.log("issuer_balance: %s", m.issuer_balance.to_text_full());
// console.log("issuer_limit: %s", m.issuer_limit.to_text_full());
var account_balance = Amount.from_json(m.account_balance);
if (!account_balance.equals(amount_req, true)) {
console.log("verify_balance: failed: %s vs %s / %s: %s",
src,
account_balance.to_text_full(),
amount_req.to_text_full(),
account_balance.not_equals_why(amount_req, true));
}
callback(!account_balance.equals(amount_req, true));
})
.request();
}
};
var verify_balances = function (remote, balances, callback) {
var tests = [];
for (var src in balances) {
var values_src = balances[src];
var values = 'string' === typeof values_src ? [ values_src ] : values_src;
for (var index in values) {
tests.push( { "source" : src, "amount" : values[index] } );
}
}
async.every(tests,
function (check, callback) {
verify_balance(remote, check.source, check.amount,
function (mismatch) { callback(!mismatch); });
},
function (every) {
callback(!every);
});
};
// --> owner: account
// --> seq: sequence number of creating transaction.
// --> taker_gets: json amount
// --> taker_pays: json amount
var verify_offer = function (remote, owner, seq, taker_pays, taker_gets, callback) {
assert(6 === arguments.length);
remote.request_ledger_entry('offer')
.offer_id(owner, seq)
.on('success', function (m) {
var wrong = !Amount.from_json(m.node.TakerGets).equals(Amount.from_json(taker_gets), true)
|| !Amount.from_json(m.node.TakerPays).equals(Amount.from_json(taker_pays), true);
if (wrong)
console.log("verify_offer: failed: %s", JSON.stringify(m));
callback(wrong);
})
.request();
};
var verify_offer_not_found = function (remote, owner, seq, callback) {
assert(4 === arguments.length);
remote.request_ledger_entry('offer')
.offer_id(owner, seq)
.on('success', function (m) {
console.log("verify_offer_not_found: found offer: %s", JSON.stringify(m));
callback('entryFound');
})
.on('error', function (m) {
// console.log("verify_offer_not_found: success: %s", JSON.stringify(m));
callback('remoteError' !== m.error
|| 'entryNotFound' !== m.remote.error);
})
.request();
};
var verify_owner_count = function (remote, account, value, callback) {
assert(4 === arguments.length);
remote.request_owner_count(account, 'CURRENT')
.once('owner_count', function (owner_count) {
if (owner_count !== value)
console.log("owner_count: %s/%d", owner_count, value);
callback(owner_count !== value);
})
.request();
};
var verify_owner_counts = function (remote, counts, callback) {
var tests = [];
for (var src in counts) {
tests.push( { "source" : src, "count" : counts[src] } );
}
async.every(tests,
function (check, callback) {
verify_owner_count(remote, check.source, check.count,
function (mismatch) { callback(!mismatch); });
},
function (every) {
callback(!every);
});
};
exports.account_dump = account_dump;
exports.build_setup = build_setup;
exports.build_teardown = build_teardown;
exports.create_accounts = create_accounts;
exports.credit_limit = credit_limit;
exports.credit_limits = credit_limits;
exports.ledger_close = ledger_close;
exports.payment = payment;
exports.payments = payments;
exports.transfer_rate = transfer_rate;
exports.verify_balance = verify_balance;
exports.verify_balances = verify_balances;
exports.verify_limit = verify_limit;
exports.verify_offer = verify_offer;
exports.verify_offer_not_found = verify_offer_not_found;
exports.verify_owner_count = verify_owner_count;
exports.verify_owner_counts = verify_owner_counts;
// vim:sw=2:sts=2:ts=8:et

View File

@@ -0,0 +1,92 @@
var assert = require('assert');
var utils = require('./testutils');
var Transaction = utils.load_module('transaction').Transaction;
var TransactionQueue = utils.load_module('transactionqueue').TransactionQueue;
describe('Transaction queue', function() {
it('Push transaction', function() {
var queue = new TransactionQueue();
var tx = new Transaction();
queue.push(tx);
assert.strictEqual(queue.length(), 1);
});
it('Remove transaction', function() {
var queue = new TransactionQueue();
var tx = new Transaction();
queue.push(tx);
queue.remove(tx);
assert.strictEqual(queue.length(), 0);
});
it('Remove transaction by ID', function() {
var queue = new TransactionQueue();
var tx = new Transaction();
queue.push(tx);
tx.submittedIDs = [
'1A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B',
'2A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'
];
queue.remove('3A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B');
assert.strictEqual(queue.length(), 1);
queue.remove('2A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B');
assert.strictEqual(queue.length(), 0);
});
it('Add sequence', function() {
var queue = new TransactionQueue();
queue.addReceivedSequence(1);
assert(queue.hasSequence(1));
});
it('Add ID', function() {
var queue = new TransactionQueue();
var tx = new Transaction();
queue.addReceivedId('1A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B', tx);
assert.strictEqual(queue.getReceived('2A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'), void(0));
assert.strictEqual(queue.getReceived('1A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'), tx);
});
it('Get submission', function() {
var queue = new TransactionQueue();
var tx = new Transaction();
queue.push(tx);
tx.submittedIDs = [
'1A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B',
'2A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'
];
assert.strictEqual(queue.getSubmission('1A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'), tx);
assert.strictEqual(queue.getSubmission('2A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'), tx);
assert.strictEqual(queue.getSubmission('3A4DEBF37496464145AA301F0AA77712E3A2BFE3480D24C3584663F800B85B5B'), void(0));
});
it('Iterate over queue', function() {
var queue = new TransactionQueue();
var count = 10;
for (var i=0; i<count; i++) {
queue.push(new Transaction());
}
queue.forEach(function(tx) {
assert(tx instanceof Transaction);
--count;
});
assert.strictEqual(count, 0);
});
});

1503
test/transaction-test.js Normal file

File diff suppressed because it is too large Load Diff

25
test/uint-test.js Normal file
View File

@@ -0,0 +1,25 @@
var assert = require('assert');
var utils = require('./testutils');
var UInt128 = utils.load_module('uint128').UInt128;
var config = require('./testutils').get_config();
describe('UInt', function() {
describe('128', function() {
describe('#parse_number', function () {
it('should create 00000000000000000000000000000000 when called with 0', function () {
var val = UInt128.from_number(0);
assert.strictEqual(val.to_hex(), '00000000000000000000000000000000');
});
it('should create 00000000000000000000000000000001 when called with 1', function () {
var val = UInt128.from_number(0);
assert.strictEqual(val.to_hex(), '00000000000000000000000000000000');
});
it('should create 000000000000000000000000FFFFFFFF when called with 0xFFFFFFFF', function () {
var val = UInt128.from_number(0xFFFFFFFF);
assert.strictEqual(val.to_hex(), '000000000000000000000000FFFFFFFF');
});
});
});
});
// vim:sw=2:sts=2:ts=8:et

View File

@@ -1,26 +1,25 @@
var fs = require("fs");
var buster = require("buster");
var fs = require('fs');
var assert = require('assert');
var utils = require('./testutils').load_module('utils');
var utils = require("../src/js/ripple/utils.js");
buster.testCase("Utils", {
"hexToString and stringToHex" : {
"Even: 123456" : function () {
buster.assert.equals("123456", utils.stringToHex(utils.hexToString("123456")));
},
"Odd: 12345" : function () {
buster.assert.equals("012345", utils.stringToHex(utils.hexToString("12345")));
},
"Under 10: 0" : function () {
buster.assert.equals("00", utils.stringToHex(utils.hexToString("0")));
},
"Under 10: 1" : function () {
buster.assert.equals("01", utils.stringToHex(utils.hexToString("1")));
},
"Empty" : function () {
buster.assert.equals("", utils.stringToHex(utils.hexToString("")));
}
}
describe('Utils', function() {
describe('hexToString and stringToHex', function() {
it('Even: 123456', function () {
assert.strictEqual('123456', utils.stringToHex(utils.hexToString('123456')));
});
it('Odd: 12345', function () {
assert.strictEqual('012345', utils.stringToHex(utils.hexToString('12345')));
});
it('Under 10: 0', function () {
assert.strictEqual('00', utils.stringToHex(utils.hexToString('0')));
});
it('Under 10: 1', function () {
assert.strictEqual('01', utils.stringToHex(utils.hexToString('1')));
});
it('Empty', function () {
assert.strictEqual('', utils.stringToHex(utils.hexToString('')));
});
});
});
// vim:sw=2:sts=2:ts=8:et

698
test/vault-test.js Normal file
View File

@@ -0,0 +1,698 @@
var assert = require('assert');
var RippleTxt = require('../src/js/ripple/rippletxt').RippleTxt;
var AuthInfo = require('../src/js/ripple/authinfo').AuthInfo;
var VaultClient = require('../src/js/ripple/vaultclient').VaultClient;
var Blob = require('../src/js/ripple/blob').Blob;
var UInt256 = require('../src/js/ripple/uint256').UInt256;
var sjcl = require('../build/sjcl');
var nock = require('nock');
var online = process.argv.indexOf('--online-blobvault') !== -1 ? true : false;
var exampleData = {
id: 'ef203d3e76552c0592384f909e6f61f1d1f02f61f07643ce015d8b0c9710dd2f',
crypt: 'f0cc91a7c1091682c245cd8e13c246cc150b2cf98b17dd6ef092019c99dc9d82',
unlock: '3e15fe3218a9c664835a6f585582e14480112110ddbe50e5028d05fc5bd9b5f4',
username: 'exampleUser',
new_username : 'exampleUser-rename',
password: 'pass word',
domain: 'staging.ripple.com',
masterkey : 'ssize4HrSYZShMWBtK6BhALGEk8VH',
email_token : '77825040-9096-4695-9cbc-76720f6a8649',
activateLink : 'https://staging.ripple.com/client/#/register/activate/',
blob: {
url: 'https://id.staging.ripple.com',
id: 'ef203d3e76552c0592384f909e6f61f1d1f02f61f07643ce015d8b0c9710dd2f',
key: 'f0cc91a7c1091682c245cd8e13c246cc150b2cf98b17dd6ef092019c99dc9d82',
data: {
auth_secret: 'd0aa918e693080a6a8d0ddc7f4dcf4bc0eecc3c3e3235f16a98661ee9c2e7a58',
account_id: 'raVUps4RghLYkVBcpMaRbVKRTTzhesPXd',
email: 'example@example.com',
contacts: [ ],
created: '2014-05-20T23:39:52.538Z',
apps: [ ],
lastSeenTxDate: 1401925490000,
identityVault: { },
revision: 2199,
encrypted_secret: 'APYqtqvjJk/J324rx2BGGzUiQ3mtmMMhMsbrUmgxb00W2aFVQzCC2mqd58Z17gzeUUcjtjAm'
}
}
};
var rippleTxtRes = "[authinfo_url]\r\nhttps://id.staging.ripple.com/v1/authinfo";
var authInfoRes = {
body : {
version: 3,
blobvault: 'https://id.staging.ripple.com',
pakdf: {
modulus: 'c7f1bc1dfb1be82d244aef01228c1409c1988943ca9e21431f1669b4aa3864c9f37f3d51b2b4ba1ab9e80f59d267fda1521e88b05117993175e004543c6e3611242f24432ce8efa3b81f0ff660b4f91c5d52f2511a6f38181a7bf9abeef72db056508bbb4eeb5f65f161dd2d5b439655d2ae7081fcc62fdcb281520911d96700c85cdaf12e7d1f15b55ade867240722425198d4ce39019550c4c8a921fc231d3e94297688c2d77cd68ee8fdeda38b7f9a274701fef23b4eaa6c1a9c15b2d77f37634930386fc20ec291be95aed9956801e1c76601b09c413ad915ff03bfdc0b6b233686ae59e8caf11750b509ab4e57ee09202239baee3d6e392d1640185e1cd',
alpha: '7283d19e784f48a96062271a5fa6e2c3addf14e6ezf78a4bb61364856d580f13552008d7b9e3b60ebd9555e9f6c7778ec69f976757d206134e54d61ba9d588a7e37a77cf48060522478352d76db000366ef669a1b1ca93c5e3e05bc344afa1e8ccb15d3343da94180dccf590c2c32408c3f3f176c8885e95d988f1565ee9b80c12f72503ab49917792f907bbb9037487b0afed967fefc9ab090164597fcd391c43fab33029b38e66ff4af96cbf6d90a01b891f856ddd3d94e9c9b307fe01e1353a8c30edd5a94a0ebba5fe7161569000ad3b0d3568872d52b6fbdfce987a687e4b346ea702e8986b03b6b1b85536c813e46052a31ed64ec490d3ba38029544aa',
url: 'https://auth1.ripple.com/api/sign',
exponent: '010001',
host: 'auth1.ripple.com'
},
exists: true,
username: 'exampleUser',
address: 'raVUps4RghLYkVBcpMaRbVKRTTzhesPXd',
emailVerified: true,
reserved: false
}
};
var authInfoNewUsernameRes = {
body : {
version: 3,
blobvault: 'https://id.staging.ripple.com',
pakdf: {
modulus: 'c7f1bc1dfb1be82d244aef01228c1409c1988943ca9e21431f1669b4aa3864c9f37f3d51b2b4ba1ab9e80f59d267fda1521e88b05117993175e004543c6e3611242f24432ce8efa3b81f0ff660b4f91c5d52f2511a6f38181a7bf9abeef72db056508bbb4eeb5f65f161dd2d5b439655d2ae7081fcc62fdcb281520911d96700c85cdaf12e7d1f15b55ade867240722425198d4ce39019550c4c8a921fc231d3e94297688c2d77cd68ee8fdeda38b7f9a274701fef23b4eaa6c1a9c15b2d77f37634930386fc20ec291be95aed9956801e1c76601b09c413ad915ff03bfdc0b6b233686ae59e8caf11750b509ab4e57ee09202239baee3d6e392d1640185e1cd',
alpha: '7283d19e784f48a96062271a5fa6e2c3addf14e6ezf78a4bb61364856d580f13552008d7b9e3b60ebd9555e9f6c7778ec69f976757d206134e54d61ba9d588a7e37a77cf48060522478352d76db000366ef669a1b1ca93c5e3e05bc344afa1e8ccb15d3343da94180dccf590c2c32408c3f3f176c8885e95d988f1565ee9b80c12f72503ab49917792f907bbb9037487b0afed967fefc9ab090164597fcd391c43fab33029b38e66ff4af96cbf6d90a01b891f856ddd3d94e9c9b307fe01e1353a8c30edd5a94a0ebba5fe7161569000ad3b0d3568872d52b6fbdfce987a687e4b346ea702e8986b03b6b1b85536c813e46052a31ed64ec490d3ba38029544aa',
url: 'https://auth1.ripple.com/api/sign',
exponent: '010001',
host: 'auth1.ripple.com'
},
exists: false,
username: exampleData.new_username,
emailVerified: false,
reserved: false
}
};
var signRes = '{"result":"success","signres":"64e9e46618fff0b720b8162e6caa209e046af128b929b766d3be421d3f048ba523453dad42597dcec01f23a5080c16695f6209d39a03668d46b782409e4a53821f70b5e6f7c8fd28eb641c504f9f9b2f378bf2ea7f19950790ac6a8832e2659800f5bb06b735bd450fa47b499fbcebeb3b0fc327619dd2171fa40fb0a41d9bcd69dd29567fa94e9466d4674b908f1cfc43822b38b94534cb37eead183b11b33761a73d78be6ba6f3a53291d4154ca0891fa59da58380e05a1e85b15a24d12406795385bcc5a6360a24ecbf068ff6f02097cd917281972d4895769f3a8668b852ea5d4232050200bcd03934f49ea0693d832980614dff1ead67ca2e0ce9073c25","modulus":"c7f1bc1dfb1be82d244aef01228c1409c198894eca9e21430f1669b4aa3864c9f37f3d51b2b4ba1ab9e80f59d267fda1521e88b05117993175e004543c6e3611242f24432ce8efa3b81f0ff660b4f91c5d52f2511a6f38181a7bf9abeef72db056508bbb4eeb5f65f161dd2d5b439655d2ae7081fcc62fdcb281520911d96700c85cdaf12e7d1f15b55ade867240722425198d4ce39019550c4c8a921fc231d3e94297688c2d77cd68ee8fdeda38b7f9a274701fef23b4eaa6c1a9c15b2d77f37634930386fc20ec291be95aed9956801e1c76601b09c413ad915ff03bfdc0b6b233686ae59e8caf11750b509ab4e57ee09202239baee3d6e392d1640185e1cd","alpha":"7283d19e784f48a96062271a4fa6e2c3addf14e6edf78a4bb61364856d580f13552008d7b9e3b60ebd9555e9f6c7778ec69f976757d206134e54d61ba9d588a7e37a77cf48060522478352d76db000366ef669a1b1ca93c5e3e05bc344afa1e8ccb15d3343da94180dccf590c2c32408c3f3f176c8885e95d988f1565ee9b80c12f72503ab49917792f907bbb9037487b0afed967fefc9ab090164597fcd391c43fab33029b38e66ff4af96cbf6d90a01b891f856ddd3d94e9c9b307fe01e1353a8c30edd5a94a0ebba5fe7161569000ad3b0d3568872d52b6fbdfce987a687e4b346ea702e8986b03b6b1b85536c813e46052a31ed64ec490d3ba38029544aa","exponent":"010001"}';
var blobRes = {
body : {
result: 'success',
encrypted_secret: 'APYqtqvjJk/J324rx2BGGzUiQ3mtmMMhMsbrUmgxb00W2aFVQzCC2mqd58Z17gzeUUcjtjAm',
blob: 'ALXga/k8mgvPpZCY0zJZdaqlptHUBL0E4V/90p4edvb7eCucU2M7aFsHIl3Z3UDu9MdlDnDU42/C+YKL1spkSTPb3rGWr0kXIFmRu8xDAd+OA3Ot7u3OBq0sN2BUHbEc47WiCue84XQHTgBh9tdeiRTqm90LJ7hZ1pD0oqr823YpFguwcC1inxFbSTNxIdWSoC3XCqZtRFM2Y5ALleWhaWKc3OwaFU6yPRcW05IBvTY/7a2SfZyklvXnJh7Bg+vfvz7ms8UCybmBgHlBPY/UqGOdZI6iFGrEQrDMFHgbxwf7bTTiaOM7Su3OsqhM1k90LvQgk3b1olb1VIMZ5J1UuTtOVTpLSsIlzgMvxxdUUyN2zMkeDE3t8kHOThhwWbLG6O+s9F9fktIv4NtoAm0dG9LtkSE1YXajk0qIYr/zrblJy7pEvNv+EzdSr+dpvssmPshgwxoHwvCwae0vL7UTmrCxIWLlHbsbU2uAzgvudJL0WOpX4W+R43U3sgMD2XysKgX783Sa7DLUWCk3Rk9eGp7c3k/XpI0IWvuKzMxID8VzdyMmXP0RE77uUufisBDtwr8gPGzS5kzU3Z/FG/dHJkfBLZdbHOffQTPKO9DKUjztWpx7CTAkN9O21XrdLK1FRAtWFTuvlA66sDYtHRaqglzFjt9DsJk7PAKi1odHeLBmYob/Bs5eK9yNnlLwu3JpHLH/jKxkuxcZ3NEdTm1WPjTdNlvT7kdGAIG9c0vIywEABkQh1kPDOe39h3GRGcUqVWJcMjJmdVDrQH7BBVV+VptCVtMOo1LviaD0MIWMiYdZyGeH5x+FkpAMjKDB3cCUkmxmis8lrDiMlnTZ5Czj+bDPp62Looc7cr2pTR2niFZRosYNgUPx6cAh7tn64RDaa/spAyv0mWyD1qRA8H0sEPmC7m7EPaBIQpODh1NFg/Bxunh+QGSmy9deINB78b9A9zLS6qWljrzg5fMDUN66xRUUKJMSD9+QJePsM4pb60vbnBBtbe04JzY7iOc/CxiT0Px6/1jlSmnY6SCtaFqtDgmQ5MLGTm1tA+aj6caT6FWsXrBboXt3eXRDPHTN+ciKELx7M3dpd4mKVWhBu7nnnVMEu1rSUrmtUStXQHod/C7vVRF2EU1hhTW7ou0hvLn+7xs9B76QeVG7iYFLiZH1qgs+upqnLCnmY3ug9yd9GQ6YwbVL1hbXJLadaOg7qhKst0KXjjjcE4G9AIEyI+UCxGdc/0PNPOCCeYEPshvonCgElGo/fAbaIuSSOFfusiovYffJ0rCkq1RagH0R/llWtUEFEDR5YFVlD3DqK6B22fQK',
revision: 2191,
email: 'example@example.com',
quota: -2975,
patches: []
}
};
var recoverRes = {
body: {
encrypted_secret: 'AAd69B9En2OF4O4LsjD+pFNeJHEGIuLh2hbla58zGvN7qU/16bDfy0QlFj8/Gu++AdFwH5U6',
revision: 2403,
blob_id: 'ef203d3e76552c0592384f909e6f61f1d1f02f61f07643ce015d8b0c9710dd2f',
blob: 'AFfW9vuHJ2J5UMnEl4WrVIT9z2d+PPVNNHkqzN64b3pKDQcRPFp8vVEqL9B+YVs/KHhFVFNxxCNyVXwO/yGg4BAslYl8Ioo11IODmOltJmb94oKR/JVyfaY4bDWaOzAoa5N/c9LHpmd0L+9igK1o260MK5OZW4BQ6EG7I+8cYi5uM2CLguiddySu2yTEnyHW47zspWP33y2deh6p5mHtLdii/tmlm7b2rKpzrRVuLN/J09jqilhMxlCEr4X065YZLlQapJ45UWvpifejEw/6Qgl1WngZxwifHa504aR/QYhb1XCNeYbkjQ1MmkTmTef47Al4r/Irzoe//pDbAFA70XXkBUVUMAXWiOxU5V6gHO4yhXbTFEn7922JZlY7PIjo2Q+BxLkozMzuh8MZdoeadqffZX1fOuyTRWfPlqi7vIYgnUyTmThKe2EZv1LsB5ZUaX3KSArKDv1xPTKS0nexGNZoFckwEfVr6B2PGbMx8LPLYEEEmd95kh8NAKN1wkOPuBehLAtbMtcnLpTsotY6diqWdW4V9BSst0KDMTxZVfeesWD7/7ga9hzNvAWO1MN3aAvDCiQVufb44i4Qfu6fLS7+nxtcDCN2PqPHcANcW0cUhUNB50ajzNwRXN8B92CiY0zkS61CzWeooHOslGp0Acau1CJy8iHGyjzbPS4ui8F2h2TbDUuInOoMqiRjXFvRTxA=',
encrypted_blobdecrypt_key: 'AA9vUokfQ1WXEOArl2DUwY3cxgXGKj9uNEqrJQzUu0hqXIWRu1V+6l1qqxXKPnm9BNscMpm0BMSbxUz++lfV50c1B4akvrzIBH+MUUgNyyPcHR7JBgjEYt0=',
patches: [],
result: 'success'
}
}
var blob = new Blob();
blob.url = exampleData.blob.url;
blob.id = exampleData.blob.id;
blob.key = exampleData.blob.key;
blob.data = exampleData.blob.data;
blob.revision = exampleData.blob.data.revision;
//must be set for self signed certs
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
while(!sjcl.random.isReady()) {
sjcl.random.addEntropy(require('crypto').randomBytes(128).toString('base64')); //add entropy to seed the generator
}
var mockRippleTxt;
var mockRippleTxt2;
var mockAuthSign;
var mockRegister;
var mockBlob;
var mockRename;
var mockUpdate;
var mockRecover;
var mockVerify;
var mockEmail;
var mockProfile;
var mockDelete;
if (!online) {
mockRippleTxt = nock('https://ripple.com')
.persist()
.get('/ripple.txt')
.reply(200, rippleTxtRes, {
'Content-Type': 'text/plain'
});
mockRippleTxt2 = nock('https://' + exampleData.domain)
.persist()
.get('/ripple.txt')
.reply(200, rippleTxtRes, {
'Content-Type': 'text/plain'
});
mockAuthSign = nock('https://auth1.ripple.com')
.persist()
.post('/api/sign')
.reply(200, signRes, {
'Content-Type': 'text/plain'
});
mockRegister = nock('https://id.staging.ripple.com').persist();
mockRegister.filteringPath(/(v1\/user\?signature(.+))/g, 'register/')
.post('/register/')
.reply(200, { result: 'error', message: 'User already exists' }, {
'Content-Type': 'application/json'
});
mockDelete = nock('https://id.staging.ripple.com').persist();
mockDelete.filteringPath(/(v1\/user\/(.+))/g, 'delete/')
.delete('/delete/')
.reply(200, { result: 'success' }, {
'Content-Type': 'application/json'
});
mockBlob = nock('https://id.staging.ripple.com').persist();
mockBlob.get('/v1/authinfo?domain=' + exampleData.domain + '&username=' + exampleData.username.toLowerCase())
.reply(200, JSON.stringify(authInfoRes.body), {
'Content-Type': 'application/json'
});
mockBlob.get('/v1/authinfo?domain=' + exampleData.domain + '&username=' + exampleData.new_username.toLowerCase())
.reply(200, JSON.stringify(authInfoNewUsernameRes.body), {
'Content-Type': 'application/json'
});
mockBlob.filteringPath(/(blob\/.+)/g, 'blob/')
.get('/v1/blob/')
.reply(200, JSON.stringify(blobRes.body), {
'Content-Type': 'application/json'
});
mockRename = nock('https://id.staging.ripple.com/v1/user/').persist();
mockRename.filteringPath(/((.+)\/rename(.+))/g, 'rename/')
.post('rename/')
.reply(200, {result:'success',message:'rename'}, {
'Content-Type': 'application/json'
});
mockUpdate = nock('https://id.staging.ripple.com/v1/user/').persist();
mockUpdate.filteringPath(/((.+)\/update(.+))/g, 'update/')
.post('update/')
.reply(200, {result:'success',message:'updateKeys'}, {
'Content-Type': 'application/json'
});
mockRecover = nock('https://id.staging.ripple.com/').persist();
mockRecover.filteringPath(/((.+)user\/recov\/(.+))/g, 'recov/')
.get('recov/')
.reply(200, recoverRes.body, {
'Content-Type': 'application/json'
});
mockVerify = nock('https://id.staging.ripple.com/v1/user/').persist();
mockVerify.filteringPath(/((.+)\/verify(.+))/g, 'verify/')
.get('verify/')
.reply(200, {result:'error', message:'invalid token'}, {
'Content-Type': 'application/json'
});
mockEmail = nock('https://id.staging.ripple.com/v1/user').persist();
mockEmail.filteringPath(/((.+)\/email(.+))/g, 'email/')
.post('email/')
.reply(200, {result:'success'}, {
'Content-Type': 'application/json'
});
mockProfile = nock('https://id.staging.ripple.com/v1/user').persist();
mockProfile.filteringPath(/((.+)\/profile(.+))/g, 'profile/')
.post('profile/')
.reply(200, {result:'success'}, {
'Content-Type': 'application/json'
});
}
describe('Ripple Txt', function () {
it('should get the content of a ripple.txt file from a given domain', function(done) {
RippleTxt.get(exampleData.domain, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
done();
});
});
it('should get currencies from a ripple.txt file for a given domain', function(done) {
RippleTxt.getCurrencies(exampleData.domain, function(err, currencies) {
assert.ifError(err);
assert(Array.isArray(currencies));
done();
});
});
it('should get the domain from a given url', function() {
var domain = RippleTxt.extractDomain("http://www.example.com");
assert.strictEqual(typeof domain, 'string');
});
});
describe('AuthInfo', function() {
it('should get auth info', function(done) {
AuthInfo.get(exampleData.domain, exampleData.username, function(err, resp) {
assert.ifError(err);
Object.keys(authInfoRes.body).forEach(function(prop) {
assert(resp.hasOwnProperty(prop));
});
done();
});
});
});
describe('VaultClient', function () {
var client = new VaultClient(exampleData.domain);
describe('#initialization', function() {
it('should be initialized with a domain', function() {
var client = new VaultClient({ domain: exampleData.domain });
assert.strictEqual(client.domain, exampleData.domain);
});
it('should default to ripple.com without a domain', function () {
var client = new VaultClient();
assert.strictEqual(client.domain, 'ripple.com');
});
});
describe('#exists', function() {
it('should determine if a username exists on the domain', function(done) {
this.timeout(10000);
client.exists(exampleData.username, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'boolean');
done();
});
});
});
describe('#login', function() {
it('with username and password should retrive the blob, crypt key, and id', function(done) {
this.timeout(10000);
client.login(exampleData.username, exampleData.password, function(err, resp) {
if (online) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert(resp.blob instanceof Blob);
assert.strictEqual(typeof resp.blob.id, 'string');
assert(UInt256.from_json(resp.blob.id).is_valid());
assert.strictEqual(typeof resp.blob.key, 'string');
assert(UInt256.from_json(resp.blob.key).is_valid());
assert.strictEqual(typeof resp.username, 'string');
assert.strictEqual(typeof resp.verified, 'boolean');
} else {
assert(err instanceof Error);
assert.strictEqual(resp, void(0));
}
done();
});
});
});
describe('#relogin', function() {
it('should retrieve the decrypted blob with blob vault url, id, and crypt key', function(done) {
this.timeout(10000);
client.relogin(exampleData.blob.url, exampleData.id, exampleData.crypt, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert(resp.blob instanceof Blob);
done();
});
});
});
describe('#unlock', function() {
it('should access the wallet secret using encryption secret, username and password', function (done) {
this.timeout(10000);
client.unlock(exampleData.username, exampleData.password, exampleData.blob.data.encrypted_secret, function(err, resp) {
if (online) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.keys, 'object');
assert.strictEqual(typeof resp.keys.unlock, 'string');
assert(UInt256.from_json(resp.keys.unlock).is_valid());
} else {
assert.strictEqual(err.toString(), 'CORRUPT: ccm: tag doesn\'t match');
assert.strictEqual(resp, void(0));
}
done();
});
});
});
describe('#loginAndUnlock', function () {
it('should get the decrypted blob and decrypted secret given name and password', function (done) {
this.timeout(10000);
client.loginAndUnlock(exampleData.username, exampleData.password, function(err, resp) {
if (online) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert(resp.blob instanceof Blob);
assert.strictEqual(typeof resp.blob.id, 'string');
assert(UInt256.from_json(resp.blob.id).is_valid());
assert.strictEqual(typeof resp.blob.key, 'string');
assert(UInt256.from_json(resp.blob.key).is_valid());
assert.strictEqual(typeof resp.unlock, 'string');
assert(UInt256.from_json(resp.unlock).is_valid());
assert.strictEqual(typeof resp.secret, 'string');
assert.strictEqual(typeof resp.username, 'string');
assert.strictEqual(typeof resp.verified, 'boolean');
} else {
assert(err instanceof Error);
assert.strictEqual(resp, void(0));
}
done();
});
});
});
describe('#register', function () {
it('should create a new blob', function (done) {
this.timeout(10000);
var options = {
username : exampleData.username,
password : exampleData.password,
email : exampleData.blob.data.email,
activateLink : exampleData.activateLink
}
client.register(options, function(err, resp) {
//fails, user already exists
assert(err instanceof Error);
assert.strictEqual(resp, void(0));
done();
});
});
});
describe('#deleteBlob', function () {
it('should remove an existing blob', function (done) {
this.timeout(10000);
var options = {
url : exampleData.blob.url,
blob_id : exampleData.blob.id,
username : online ? "" : exampleData.username,
account_id : exampleData.blob.data.account_id,
masterkey : exampleData.masterkey
}
client.deleteBlob(options, function(err, resp) {
if (online) {
//removing the username will result in an error from the server
assert(err instanceof Error);
assert.strictEqual(resp, void(0));
} else {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
}
done();
});
});
});
describe('#updateProfile', function () {
it('should update profile parameters associated with a blob', function (done) {
this.timeout(10000);
var options = {
url : exampleData.blob.url,
blob_id : exampleData.blob.id,
username : exampleData.username,
auth_secret : exampleData.blob.data.auth_secret,
profile : {
city : "San Francisco",
phone : "555-555-5555"
}
}
client.updateProfile(options, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
done();
});
});
});
});
describe('Blob', function () {
var client;
var resp;
client = new VaultClient({ domain: exampleData.domain });
before(function(done) {
if (online) {
this.timeout(10000);
client.login(exampleData.username, exampleData.password, function(err, res) {
resp = res;
blob = res.blob;
done();
});
} else {
mockBlob.filteringPath(/(blob\/.+)/g, 'blob/')
.post('/v1/blob/')
.reply(200, {result:'success'}, {
'Content-Type': 'application/json'
});
done();
}
});
describe('#rename', function () {
it('should change the username of a blob', function (done) {
this.timeout(20000);
var options = {
username : exampleData.username,
new_username : exampleData.new_username,
password : exampleData.password,
masterkey : exampleData.masterkey,
blob : blob
}
client.rename(options, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
assert.strictEqual(typeof resp.message, 'string');
if (online) {
options.username = exampleData.new_username;
options.new_username = exampleData.username;
//change it back
client.rename(options, function(err,resp){
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
assert.strictEqual(typeof resp.message, 'string');
done();
});
} else {
done();
}
});
});
});
describe('#changePassword', function () {
it('should change the password and keys of a blob', function (done) {
this.timeout(10000);
var options = {
username : exampleData.username,
password : exampleData.password,
masterkey : exampleData.masterkey,
blob : blob
}
client.changePassword(options, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
assert.strictEqual(typeof resp.message, 'string');
done();
});
});
});
describe('#recoverBlob', function () {
it('should recover the blob given a username and secret', function (done) {
this.timeout(10000);
var options = {
url : exampleData.blob.url,
username : exampleData.username,
masterkey : exampleData.masterkey,
}
client.recoverBlob(options, function(err, blob) {
assert.ifError(err);
assert(blob instanceof Blob);
done();
});
});
});
describe('#verifyEmail', function () {
it('should verify an email given a username and token', function (done) {
this.timeout(10000);
client.verify(exampleData.username, exampleData.email_token, function(err, resp) {
//result will be error, because of invalid token
assert(err instanceof Error);
assert.strictEqual(resp, void(0));
done();
});
});
});
describe('#resendVerifcationEmail', function () {
it('should resend a verification given options', function (done) {
this.timeout(10000);
var options = {
url : exampleData.blob.url,
id : exampleData.blob.id,
username : exampleData.username,
account_id : exampleData.blob.data.account_id,
email : exampleData.blob.data.email,
activateLink : exampleData.activateLink,
masterkey : exampleData.masterkey
}
client.resendEmail(options, function(err, resp) {
assert.ifError(err);
assert.strictEqual(typeof resp, 'object');
assert.strictEqual(typeof resp.result, 'string');
done();
});
});
});
it('#set', function(done) {
this.timeout(10000)
blob.extend('/testObject', {
foo: [],
}, function(err, resp) {
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#extend', function(done) {
this.timeout(10000)
blob.extend('/testObject', {
foobar: 'baz',
}, function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#unset', function(done) {
this.timeout(10000)
blob.unset('/testObject', function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#unshift', function(done) {
this.timeout(10000)
blob.unshift('/testArray', {
name: 'bob',
address: '1234'
}, function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#filter', function(done) {
this.timeout(10000)
blob.filter('/testArray', 'name', 'bob', 'extend', '', {description:'Alice'}, function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#consolidate', function(done) {
this.timeout(10000)
blob.unset('/testArray', function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
blob.consolidate(function(err, resp){
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
});
describe('identity', function() {
it('#identity_set', function (done) {
this.timeout(10000);
blob.identity.set('address', exampleData.unlock, {city:"San Francisco", region:"CA"}, function (err, resp) {
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
it('#identity_get', function () {
var property = blob.identity.get('address', exampleData.unlock);
assert.ifError(property.error);
assert.strictEqual(typeof property.encrypted, 'boolean');
assert.notEqual(typeof property.value, 'undefined');
});
it('#identity_getAll', function () {
var obj = blob.identity.getAll(exampleData.unlock);
assert.strictEqual(typeof obj, 'object');
});
it('#identity_getFullAddress', function () {
var address = blob.identity.getFullAddress(exampleData.unlock);
assert.strictEqual(typeof address, 'string');
});
it('#identity_unset', function (done) {
this.timeout(10000);
blob.identity.unset('name', exampleData.unlock, function (err, resp) {
assert.ifError(err);
assert.strictEqual(resp.result, 'success');
done();
});
});
});
if (!online) {
after(function () {
nock.restore();
});
}
});

View File

@@ -1 +1,40 @@
module.exports = WebSocket;
// If there is no WebSocket, try MozWebSocket (support for some old browsers)
try {
module.exports = WebSocket;
} catch(err) {
module.exports = MozWebSocket;
}
// Some versions of Safari Mac 5 and Safari iOS 4 seem to support websockets,
// but can't communicate with websocketpp, which is what rippled uses.
//
// Note that we check for both the WebSocket protocol version the browser seems
// to implement as well as the user agent etc. The reason is that we want to err
// on the side of trying to connect since we don't want to accidentally disable
// a browser that would normally work fine.
var match, versionRegexp = /Version\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//;
if (
// Is browser
"object" === typeof navigator &&
"string" === typeof navigator.userAgent &&
// Is Safari
(match = versionRegexp.exec(navigator.userAgent)) &&
// And uses the old websocket protocol
2 === window.WebSocket.CLOSED
) {
// Is iOS
if (/iP(hone|od|ad)/.test(navigator.platform)) {
// Below version 5 is broken
if (+match[1] < 5) {
module.exports = void(0);
}
// Is any other Mac OS
// If you want to refactor this code, be careful, iOS user agents contain the
// string "like Mac OS X".
} else if (navigator.appVersion.indexOf("Mac") !== -1) {
// Below version 6 is broken
if (+match[1] < 6) {
module.exports = void(0);
}
}
}