mirror of
https://github.com/Xahau/xahau.js.git
synced 2025-11-04 21:15:47 +00:00
Compare commits
787 Commits
0.7.35
...
0.12.1-rc3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25bb9c7320 | ||
|
|
a160e16abd | ||
|
|
ec31841aa5 | ||
|
|
3e249902c4 | ||
|
|
21bb766f06 | ||
|
|
a883151400 | ||
|
|
3c7fe82cbd | ||
|
|
899fc09704 | ||
|
|
daa45a44b9 | ||
|
|
52494628c3 | ||
|
|
dbf5d21b72 | ||
|
|
441bd4dfbf | ||
|
|
8452f05dda | ||
|
|
0d2325e646 | ||
|
|
90329d3d73 | ||
|
|
ca83a142f8 | ||
|
|
d3b2d3d5c5 | ||
|
|
255177487c | ||
|
|
ed0b75bcde | ||
|
|
06500a7909 | ||
|
|
6e16bf68ae | ||
|
|
ad22480117 | ||
|
|
2fcd09072f | ||
|
|
f0c785b196 | ||
|
|
84fe76bada | ||
|
|
b5ed8f59a7 | ||
|
|
52526f90d7 | ||
|
|
99e6e81e65 | ||
|
|
5af824f5cf | ||
|
|
2166bb2e88 | ||
|
|
ae884c0200 | ||
|
|
423ec7d08a | ||
|
|
914cd6ecb2 | ||
|
|
f221c82859 | ||
|
|
d57be723e6 | ||
|
|
777554809a | ||
|
|
f2b63fa4a8 | ||
|
|
4d06ce7454 | ||
|
|
8da6ec5fa3 | ||
|
|
2a5a8b498d | ||
|
|
a9b7d7d793 | ||
|
|
6578cf5dd7 | ||
|
|
2e21e8a43c | ||
|
|
176e1fd9d4 | ||
|
|
c3b274b18f | ||
|
|
8e134918fb | ||
|
|
2b531d2a1f | ||
|
|
87317dd54a | ||
|
|
618548c88d | ||
|
|
b62f42006c | ||
|
|
c275174f27 | ||
|
|
af4ed295e0 | ||
|
|
7614a03ea8 | ||
|
|
d9527726b6 | ||
|
|
05f4099709 | ||
|
|
a20a649013 | ||
|
|
0e3e64105c | ||
|
|
b2cdb1a6ae | ||
|
|
812432db96 | ||
|
|
5b2c4aef2d | ||
|
|
b7ccf424f4 | ||
|
|
77d5db168b | ||
|
|
e80cd1ff55 | ||
|
|
4ff25a21f6 | ||
|
|
f184a71360 | ||
|
|
fc38a9853d | ||
|
|
6023efed41 | ||
|
|
2abac6ce5c | ||
|
|
53c7705c36 | ||
|
|
7059ab65d6 | ||
|
|
e133988b36 | ||
|
|
9af27e7964 | ||
|
|
a57b3835fb | ||
|
|
451cbb809e | ||
|
|
fd1b64393d | ||
|
|
ed875a35b4 | ||
|
|
e85b0c2122 | ||
|
|
f5b192f55f | ||
|
|
ff86d5381d | ||
|
|
b63ac4addb | ||
|
|
3e1a66d617 | ||
|
|
93ed5a8cae | ||
|
|
2e6e8807be | ||
|
|
1ed36fabdb | ||
|
|
8dc40ee379 | ||
|
|
db4c7c89e3 | ||
|
|
f9bc7cc746 | ||
|
|
8f87ed65f9 | ||
|
|
39c37631f3 | ||
|
|
d0fb291c4e | ||
|
|
793523cbe9 | ||
|
|
6da4dd9ecc | ||
|
|
79892af8f8 | ||
|
|
b86790c854 | ||
|
|
c8f18c8c85 | ||
|
|
b19ecb4482 | ||
|
|
ba9af55aca | ||
|
|
35d76b3520 | ||
|
|
a5a0326092 | ||
|
|
a05833f845 | ||
|
|
c5deb60510 | ||
|
|
ff2ff89e3e | ||
|
|
35a346a674 | ||
|
|
1217a95c52 | ||
|
|
d025b4a0c3 | ||
|
|
2cab50f920 | ||
|
|
b049278dde | ||
|
|
93335e74cb | ||
|
|
2833a7b66e | ||
|
|
0d05b960f7 | ||
|
|
9fd64a9209 | ||
|
|
1637d26de3 | ||
|
|
525ff9b75e | ||
|
|
42e7932f59 | ||
|
|
98f40abfc3 | ||
|
|
55cd13ed4e | ||
|
|
7cb113fcbc | ||
|
|
ddbb999194 | ||
|
|
1db96829ed | ||
|
|
3498dea18c | ||
|
|
97a8c87490 | ||
|
|
fa72e09840 | ||
|
|
d8cad710a5 | ||
|
|
f91dcc33d3 | ||
|
|
e5f524ec56 | ||
|
|
f9b13cbc7f | ||
|
|
c7e0ba68f6 | ||
|
|
220262d192 | ||
|
|
1f860ecba6 | ||
|
|
69a13b71ea | ||
|
|
0a27afe6ee | ||
|
|
a3de021cd2 | ||
|
|
4dcbe78e83 | ||
|
|
84a8e8cbf6 | ||
|
|
e4b2b3d06b | ||
|
|
000a2ea00c | ||
|
|
89de91301e | ||
|
|
6be84bfa73 | ||
|
|
6cd79e7237 | ||
|
|
11d73173b8 | ||
|
|
9b3d62b765 | ||
|
|
2bdff53e68 | ||
|
|
8af5f9c28e | ||
|
|
9f71abf978 | ||
|
|
3fc2d3c1d9 | ||
|
|
c0c8db6dcc | ||
|
|
27249c0bb4 | ||
|
|
62e9684542 | ||
|
|
74b006cb0b | ||
|
|
77b33f11ab | ||
|
|
0aba638e6e | ||
|
|
e82522349f | ||
|
|
e520700260 | ||
|
|
3ec335f3a6 | ||
|
|
0f212e4dd1 | ||
|
|
c263654c88 | ||
|
|
874e3f24a6 | ||
|
|
b14343f3cf | ||
|
|
732b50dea7 | ||
|
|
be3bbe9b61 | ||
|
|
51211bbba0 | ||
|
|
5d1ff1c912 | ||
|
|
ea1be4fc50 | ||
|
|
7cc05f0d92 | ||
|
|
54606f3c21 | ||
|
|
a5d1705930 | ||
|
|
bfc0fb6c88 | ||
|
|
d1d4452217 | ||
|
|
2166a434a3 | ||
|
|
1053fa18e1 | ||
|
|
fa147d467e | ||
|
|
3f61598d6c | ||
|
|
9bf3724ce6 | ||
|
|
c2f27a4deb | ||
|
|
b6b99dde02 | ||
|
|
1fd0f4a8fe | ||
|
|
67d39737a4 | ||
|
|
aef4fe29a3 | ||
|
|
34c0677c45 | ||
|
|
3cb4a64b47 | ||
|
|
0db0375a5e | ||
|
|
47e6bdc644 | ||
|
|
66c2e27711 | ||
|
|
72387873b4 | ||
|
|
59017bc0bd | ||
|
|
2dde114d3d | ||
|
|
9e89904f03 | ||
|
|
56d0aca254 | ||
|
|
239710cebf | ||
|
|
1eaad617cb | ||
|
|
3c21994adc | ||
|
|
d15d14e197 | ||
|
|
e32694dc79 | ||
|
|
6ec8124287 | ||
|
|
2222adfc10 | ||
|
|
fcc2377657 | ||
|
|
1704ac4ae1 | ||
|
|
666e4348e0 | ||
|
|
9b22f279bc | ||
|
|
0835de983b | ||
|
|
1a892d58fc | ||
|
|
73a3cce4a4 | ||
|
|
d5ef4774fa | ||
|
|
c5bd4239a4 | ||
|
|
634e811888 | ||
|
|
3204998fcb | ||
|
|
12e428733a | ||
|
|
9cc6ad09a9 | ||
|
|
84abb5962e | ||
|
|
4bba55d2dc | ||
|
|
b4cabad44e | ||
|
|
28cc0f9e3b | ||
|
|
95a2cc18fe | ||
|
|
8e315a9859 | ||
|
|
89adcf4f4e | ||
|
|
3a6c5e41c9 | ||
|
|
86ed24b94c | ||
|
|
c792c471c3 | ||
|
|
e371cc2c3c | ||
|
|
ccf218c8f0 | ||
|
|
0d7fc0a573 | ||
|
|
74cacd5209 | ||
|
|
bb79cf2a87 | ||
|
|
28451df1a8 | ||
|
|
38e288f62a | ||
|
|
905f908450 | ||
|
|
672171fd0c | ||
|
|
520660ecbc | ||
|
|
06acb5faf2 | ||
|
|
d43fa03f05 | ||
|
|
baed1aaf92 | ||
|
|
cc229e803c | ||
|
|
d6b1728c23 | ||
|
|
bc5dcc359c | ||
|
|
ced07e1d6b | ||
|
|
cffffd9591 | ||
|
|
b8766e263f | ||
|
|
fc426d5764 | ||
|
|
056d2381cd | ||
|
|
2932a0ec5f | ||
|
|
d3d85a3fcf | ||
|
|
7a1feaa897 | ||
|
|
5f3cf72cc6 | ||
|
|
cae980788e | ||
|
|
df763b8765 | ||
|
|
365085809e | ||
|
|
3ee7998261 | ||
|
|
6fb9ed8312 | ||
|
|
89f79c35f5 | ||
|
|
6bdd4b2670 | ||
|
|
acd79d19e2 | ||
|
|
674d4a957d | ||
|
|
bdbf264771 | ||
|
|
8f17873da2 | ||
|
|
b0cac776ee | ||
|
|
625dba4d85 | ||
|
|
261b72d0fc | ||
|
|
b5b167ef6d | ||
|
|
66d21b24cd | ||
|
|
5a084ea3cc | ||
|
|
486944fa4c | ||
|
|
b63a76d298 | ||
|
|
31045039c0 | ||
|
|
6f5d1104aa | ||
|
|
3c9660203b | ||
|
|
29e1423f84 | ||
|
|
e42e67e259 | ||
|
|
ed018282c4 | ||
|
|
fbe015758c | ||
|
|
7e24a81764 | ||
|
|
9ab77e90fe | ||
|
|
ae3ed699db | ||
|
|
0c22a9753e | ||
|
|
a447f6b723 | ||
|
|
a8ef614b81 | ||
|
|
9025e8bfa8 | ||
|
|
722f4e175d | ||
|
|
1ad6e5a15f | ||
|
|
3554572db7 | ||
|
|
f1abff962f | ||
|
|
f05941fbc4 | ||
|
|
237c46d5a0 | ||
|
|
76cfb69d9f | ||
|
|
7610df0fbb | ||
|
|
8bc935aa62 | ||
|
|
24587fab9c | ||
|
|
0248475473 | ||
|
|
d2fa5c4b12 | ||
|
|
c60c0cb6e0 | ||
|
|
cdf1112666 | ||
|
|
d861bb2e34 | ||
|
|
006849a3d5 | ||
|
|
a3c1d06eba | ||
|
|
4bd1e7a2bc | ||
|
|
68643f3118 | ||
|
|
560dfc8ae6 | ||
|
|
b0459e096b | ||
|
|
2a0dfc4587 | ||
|
|
2dcd5f94fb | ||
|
|
13685d03e1 | ||
|
|
278df9025a | ||
|
|
cb608406f8 | ||
|
|
f4a55d03d3 | ||
|
|
d3b6b8127c | ||
|
|
bc1f9f8a28 | ||
|
|
9a5c9aea75 | ||
|
|
f1004c6db2 | ||
|
|
7708c64576 | ||
|
|
0527b8c981 | ||
|
|
13f89e2fcc | ||
|
|
69a0a473a6 | ||
|
|
4ab82d7e01 | ||
|
|
4be209e286 | ||
|
|
8b10325895 | ||
|
|
70bf600247 | ||
|
|
d42e06d48b | ||
|
|
9c080b6790 | ||
|
|
033257b03b | ||
|
|
39d8bcdfc2 | ||
|
|
2ddcb4e2b7 | ||
|
|
d972718a53 | ||
|
|
6abed8dd53 | ||
|
|
e74e697b45 | ||
|
|
26c59e8565 | ||
|
|
a5e83c4f23 | ||
|
|
900c4bbd2e | ||
|
|
947ec3edc2 | ||
|
|
957f10d9f1 | ||
|
|
89aa54dff8 | ||
|
|
bb76530e4b | ||
|
|
011e2cc1e3 | ||
|
|
4c594f8964 | ||
|
|
1fcfcf2392 | ||
|
|
6311abff81 | ||
|
|
ed2da57475 | ||
|
|
778ccd4805 | ||
|
|
327c35252f | ||
|
|
5e7af2fba4 | ||
|
|
dce15bc579 | ||
|
|
d5e32db954 | ||
|
|
bdfa83592b | ||
|
|
23e473b688 | ||
|
|
0dfd3a0ae0 | ||
|
|
d107092540 | ||
|
|
c2f379d3b3 | ||
|
|
57b70300f5 | ||
|
|
eeba86f9c5 | ||
|
|
e0d68e60ec | ||
|
|
254248486b | ||
|
|
1b57cc6d35 | ||
|
|
77234f256d | ||
|
|
795d31d2db | ||
|
|
f3f10fd9bd | ||
|
|
7100b4be8d | ||
|
|
b1a7200d1b | ||
|
|
5d8bb541c6 | ||
|
|
b51c59b23a | ||
|
|
2cd434e861 | ||
|
|
1599eb9629 | ||
|
|
8ef7481858 | ||
|
|
344d478b3f | ||
|
|
39b7e27aa6 | ||
|
|
b1876b4f77 | ||
|
|
db3b41d1ba | ||
|
|
02b5d14d0f | ||
|
|
0120044c96 | ||
|
|
ad6304e857 | ||
|
|
7cba84b8cf | ||
|
|
5a9a4be163 | ||
|
|
4d1a31d3c9 | ||
|
|
6e3ceec4e5 | ||
|
|
bc7d3c0af8 | ||
|
|
519ddee092 | ||
|
|
3e0fcc5b8b | ||
|
|
b1972985c4 | ||
|
|
51c42e9257 | ||
|
|
86dcbcc671 | ||
|
|
3b7cd9d84f | ||
|
|
1073ec6214 | ||
|
|
14a5e42a63 | ||
|
|
b4564a86b4 | ||
|
|
03386a61e9 | ||
|
|
8bb2623360 | ||
|
|
ab0e4188b3 | ||
|
|
42c853dbf4 | ||
|
|
ce48a1793b | ||
|
|
6177543d98 | ||
|
|
9697bfa817 | ||
|
|
70425ab5c8 | ||
|
|
7cccb451d2 | ||
|
|
a39fb9d551 | ||
|
|
8f7cdc6e4f | ||
|
|
8f7e365b03 | ||
|
|
64735e523f | ||
|
|
f126610219 | ||
|
|
2caef539ce | ||
|
|
468fb87749 | ||
|
|
4f4808ff15 | ||
|
|
e6bbca7df1 | ||
|
|
e7d1095be2 | ||
|
|
a08d5ce6e5 | ||
|
|
fec2f5578d | ||
|
|
4869e30914 | ||
|
|
e1f31765e7 | ||
|
|
a3668defa8 | ||
|
|
765ff9fa32 | ||
|
|
dd04177f83 | ||
|
|
2e2ab6bffc | ||
|
|
934cacfc1b | ||
|
|
9800fd8f11 | ||
|
|
3e84996788 | ||
|
|
5a3f55d774 | ||
|
|
dbddc314a6 | ||
|
|
c98f875811 | ||
|
|
29a1ffb3b8 | ||
|
|
17770ad4c9 | ||
|
|
cc9ed435eb | ||
|
|
27a723b453 | ||
|
|
af6c9b6bd2 | ||
|
|
2d3bbecb05 | ||
|
|
51e4cb15b4 | ||
|
|
5ce91a027c | ||
|
|
3cb337e7ec | ||
|
|
c29f92f05b | ||
|
|
01903cc6d2 | ||
|
|
fff7a6bc9e | ||
|
|
678c67622d | ||
|
|
2a6aec94fb | ||
|
|
bc52f33e9c | ||
|
|
006beeb5f9 | ||
|
|
ff85b3c4c9 | ||
|
|
6c7b2b17dc | ||
|
|
131de6661c | ||
|
|
d416f31801 | ||
|
|
8885a9e3e5 | ||
|
|
27e100f4ee | ||
|
|
40dc49bd63 | ||
|
|
989509dc07 | ||
|
|
9c3f5fbcd2 | ||
|
|
0917f66cb2 | ||
|
|
66c56df7dc | ||
|
|
b5fdfa2604 | ||
|
|
a0d4a3c84d | ||
|
|
d8374b2f49 | ||
|
|
a2a2162f48 | ||
|
|
d845d094db | ||
|
|
81e805fcb9 | ||
|
|
81283eeb84 | ||
|
|
60069d0a28 | ||
|
|
7c0561d17f | ||
|
|
45ac10b215 | ||
|
|
47f5943cf7 | ||
|
|
73d30242c9 | ||
|
|
5a4e33a02d | ||
|
|
edbbbec8f3 | ||
|
|
f8811f27a0 | ||
|
|
ad6138a14e | ||
|
|
e6fec67ce9 | ||
|
|
08a09fab9c | ||
|
|
1bf06bc656 | ||
|
|
cf46808557 | ||
|
|
df5a8656f6 | ||
|
|
b41f00515b | ||
|
|
2b22b49f83 | ||
|
|
4c0eda95c6 | ||
|
|
92e4644d60 | ||
|
|
11b67b15e4 | ||
|
|
565cd59f13 | ||
|
|
f4643c7b52 | ||
|
|
a292c2841c | ||
|
|
edd57a89c1 | ||
|
|
0d3bc96672 | ||
|
|
cc96d21da6 | ||
|
|
ed4e07907f | ||
|
|
da6e4be815 | ||
|
|
391cba18b6 | ||
|
|
49f55cea48 | ||
|
|
fc361841b0 | ||
|
|
5db493df1c | ||
|
|
ca317f01db | ||
|
|
2687830623 | ||
|
|
4d9603ae7b | ||
|
|
61087c9406 | ||
|
|
4d6251be37 | ||
|
|
18b817c284 | ||
|
|
61649b1428 | ||
|
|
c9f82be54c | ||
|
|
416dc44d05 | ||
|
|
97712bfe96 | ||
|
|
f923a62f54 | ||
|
|
a41c5ddc62 | ||
|
|
564f248fe0 | ||
|
|
e712034c0f | ||
|
|
ca88298b76 | ||
|
|
5ac21f993e | ||
|
|
5eb12c9d28 | ||
|
|
e12bea4b27 | ||
|
|
cad9521049 | ||
|
|
0847002c96 | ||
|
|
c3783533e9 | ||
|
|
85a7e935b2 | ||
|
|
43658264a8 | ||
|
|
b00f5c5a1c | ||
|
|
7af758bf88 | ||
|
|
c1a0be2402 | ||
|
|
1d4bcd4e0f | ||
|
|
4450ef822e | ||
|
|
ef74c7ca11 | ||
|
|
27eadc5587 | ||
|
|
0b03de66e7 | ||
|
|
cfcea4affb | ||
|
|
4e13170123 | ||
|
|
fe4cf94b62 | ||
|
|
f4233d7615 | ||
|
|
6e5bebfe81 | ||
|
|
21b0e09837 | ||
|
|
7b243dff03 | ||
|
|
fbe67df069 | ||
|
|
ea82c8cce3 | ||
|
|
e5322fb8e4 | ||
|
|
c5e6c5819b | ||
|
|
c3975dfc68 | ||
|
|
ddf7ca78ee | ||
|
|
71d8b6c9bf | ||
|
|
f11cd65494 | ||
|
|
59f7d49b80 | ||
|
|
447ae3f38f | ||
|
|
b2c4f935e7 | ||
|
|
5a85385db6 | ||
|
|
6dcd9e9014 | ||
|
|
eebfe02163 | ||
|
|
19294f5435 | ||
|
|
ef17cd86a8 | ||
|
|
ac62a336ea | ||
|
|
bdb7454737 | ||
|
|
4e9082f4d9 | ||
|
|
7daa4b4c3b | ||
|
|
7be13bebfc | ||
|
|
aea75f2beb | ||
|
|
cb59f86d4c | ||
|
|
8f340c1cde | ||
|
|
76659b613b | ||
|
|
79c5428da2 | ||
|
|
ca2d137d52 | ||
|
|
9789f76f64 | ||
|
|
df6eee1084 | ||
|
|
09461fb3c8 | ||
|
|
5607f2d379 | ||
|
|
3b7f556887 | ||
|
|
e84633de13 | ||
|
|
2b2267c46e | ||
|
|
37090716d3 | ||
|
|
3535ce1b04 | ||
|
|
dda865b6f2 | ||
|
|
9115a7193d | ||
|
|
6d347bcec0 | ||
|
|
b96d26acc2 | ||
|
|
5dbfe04a9a | ||
|
|
7e11b4e03d | ||
|
|
e2eaf9718c | ||
|
|
2576abe06e | ||
|
|
07a15d7b91 | ||
|
|
c5fdb3e2f6 | ||
|
|
0b068dab6a | ||
|
|
b4497bcb08 | ||
|
|
3baea7752f | ||
|
|
05cce3dbab | ||
|
|
d23dca2ef1 | ||
|
|
bcf93e230e | ||
|
|
4bd39b9bb1 | ||
|
|
8797cdb27e | ||
|
|
ab259fa519 | ||
|
|
585ca4160d | ||
|
|
5fe1ebdd45 | ||
|
|
a0ba289848 | ||
|
|
b6f0aa3914 | ||
|
|
a47eef3283 | ||
|
|
e0bcf19340 | ||
|
|
fa9305626b | ||
|
|
a573465e41 | ||
|
|
9527d6ed22 | ||
|
|
3ef60e0391 | ||
|
|
6028115e52 | ||
|
|
fd0dc3b330 | ||
|
|
3ebcadfad4 | ||
|
|
301b34a923 | ||
|
|
f963d266a2 | ||
|
|
309957a6cf | ||
|
|
47094f84d7 | ||
|
|
68c86bf672 | ||
|
|
e6782f4563 | ||
|
|
1b2b19381b | ||
|
|
d495f397b0 | ||
|
|
f1a58de348 | ||
|
|
01c6417425 | ||
|
|
6ae186951b | ||
|
|
8d77ff9af7 | ||
|
|
eeb5e22e9a | ||
|
|
fc5284cc88 | ||
|
|
6a7eb132bd | ||
|
|
f8519584d2 | ||
|
|
58b307411e | ||
|
|
c7dd3cc70e | ||
|
|
dc62dbe022 | ||
|
|
e50ddd6237 | ||
|
|
6a55dbc55e | ||
|
|
4e7cf460ec | ||
|
|
87dd8d535a | ||
|
|
ce6010ecd3 | ||
|
|
ac5f146187 | ||
|
|
14b2697a52 | ||
|
|
a4078e10e9 | ||
|
|
06796aa7c0 | ||
|
|
62d4be0185 | ||
|
|
2e0536ea2d | ||
|
|
94c7408b5b | ||
|
|
1186b4a314 | ||
|
|
1cccf01bf2 | ||
|
|
8f7cda3c2c | ||
|
|
c95ac13946 | ||
|
|
ee1ce36045 | ||
|
|
a4f22d8b42 | ||
|
|
2afce7cf54 | ||
|
|
6150721951 | ||
|
|
61b3ef0205 | ||
|
|
06108ffee3 | ||
|
|
726b309085 | ||
|
|
ff14b55ea5 | ||
|
|
bb82eb9219 | ||
|
|
abc43f80e0 | ||
|
|
f6343dc1d1 | ||
|
|
182e1863f4 | ||
|
|
0a8d4ad587 | ||
|
|
48e49ac42b | ||
|
|
1579d58edf | ||
|
|
61cb21188d | ||
|
|
49d50c02d4 | ||
|
|
b7f7e6dc60 | ||
|
|
e49bb4e527 | ||
|
|
44a9724b2a | ||
|
|
7af4a376a2 | ||
|
|
77e69efe19 | ||
|
|
da8061ed52 | ||
|
|
90d65573b5 | ||
|
|
838180a498 | ||
|
|
5ebab2fe28 | ||
|
|
0ff0004d42 | ||
|
|
b931b92773 | ||
|
|
ad08e20085 | ||
|
|
c1c18c465d | ||
|
|
a71fc07ba5 | ||
|
|
89c4839fa5 | ||
|
|
41ee43740e | ||
|
|
179c215b15 | ||
|
|
9100e8ecc0 | ||
|
|
fb213e5818 | ||
|
|
ac12e3fb5c | ||
|
|
caa78b11dd | ||
|
|
61586a4185 | ||
|
|
a7df5248c9 | ||
|
|
cf53ec9da8 | ||
|
|
46e966fb7f | ||
|
|
01e38ed4ca | ||
|
|
01459061ee | ||
|
|
3ef105e077 | ||
|
|
decebe3d2e | ||
|
|
2a832777a7 | ||
|
|
6a718c4384 | ||
|
|
a1face76b7 | ||
|
|
8104f71162 | ||
|
|
1ce2a517aa | ||
|
|
53c7836a7a | ||
|
|
160b6e8a51 | ||
|
|
b1f6284813 | ||
|
|
d104ebb6f5 | ||
|
|
017713c435 | ||
|
|
644ca2b472 | ||
|
|
453ff91065 | ||
|
|
8b79ec0e5a | ||
|
|
95b7858c8f | ||
|
|
5ef7e5462e | ||
|
|
54a2655bc2 | ||
|
|
785a066ebb | ||
|
|
fa60b182a3 | ||
|
|
dbc965de3c | ||
|
|
77814b791d | ||
|
|
ddf12d43c3 | ||
|
|
f5b59b4268 | ||
|
|
58e14f3bb3 | ||
|
|
1c02166662 | ||
|
|
0e5c29269f | ||
|
|
9a349a3d55 | ||
|
|
d5e01adbf9 | ||
|
|
61bc01ae12 | ||
|
|
c3568de8b3 | ||
|
|
eca5ac7611 | ||
|
|
a8e0cb2e0b | ||
|
|
799bb5faeb | ||
|
|
0b5c0722e0 | ||
|
|
3964e4522e | ||
|
|
bdb299e085 | ||
|
|
349ca81cc9 | ||
|
|
77a323aaae | ||
|
|
8be08b5e73 | ||
|
|
b53b05496d | ||
|
|
bd2dba7f15 | ||
|
|
81e0e2672d | ||
|
|
bd65c6e6d0 | ||
|
|
396d7b07d8 | ||
|
|
55184162d1 | ||
|
|
beffd0864a | ||
|
|
5ba7c31e4c | ||
|
|
b26129db72 | ||
|
|
1693a57845 | ||
|
|
7ea1ba168d | ||
|
|
7fe530e82c | ||
|
|
7e4ae26b8f | ||
|
|
963e1d58cb | ||
|
|
cc6f683590 | ||
|
|
da3af124ba | ||
|
|
b342cf1edf | ||
|
|
a1989b3931 | ||
|
|
80bdce970a | ||
|
|
7cf80a468d | ||
|
|
bee632e1e2 | ||
|
|
7901e12b0a | ||
|
|
8979a3cf02 | ||
|
|
9025119f8d | ||
|
|
fdaa63c132 | ||
|
|
9e825e927c | ||
|
|
4929d63073 | ||
|
|
5b0dd33fa8 | ||
|
|
5203a1e868 | ||
|
|
27645c234a | ||
|
|
5280d994a2 | ||
|
|
12f43a5334 | ||
|
|
4f0399180c | ||
|
|
ea11d34254 | ||
|
|
a222f2be98 | ||
|
|
a48a25e236 | ||
|
|
e4f9be5af8 | ||
|
|
473d8a8d8c | ||
|
|
41ea820ae0 | ||
|
|
0558ad689a | ||
|
|
3199aa438a | ||
|
|
c3f630c27f | ||
|
|
cf3a21a712 | ||
|
|
d8504a3001 | ||
|
|
a2b07d5edd | ||
|
|
13a6a2c335 | ||
|
|
e19be192bd | ||
|
|
c32216c9e5 | ||
|
|
904082a86c | ||
|
|
f56a20d697 | ||
|
|
8275e036c9 | ||
|
|
903e480130 | ||
|
|
30fd0e7bff | ||
|
|
fbdef6eea0 | ||
|
|
5a04ce9629 | ||
|
|
693e2aaae7 | ||
|
|
43deeaf5fb | ||
|
|
cbba7727f2 | ||
|
|
52e1665e72 | ||
|
|
66ea770287 | ||
|
|
18efa5d742 | ||
|
|
802212bbdc | ||
|
|
7f59fb917c | ||
|
|
6ebaec31a5 | ||
|
|
14f409ff56 | ||
|
|
8ffd0b13a3 | ||
|
|
969873441e | ||
|
|
282ac6d8ab | ||
|
|
1e3c96b14f | ||
|
|
b14fab8aa7 | ||
|
|
be33b1be60 | ||
|
|
06288e798e | ||
|
|
0de7d84862 | ||
|
|
58afce517a | ||
|
|
250e987fd9 | ||
|
|
87ba2abc9a | ||
|
|
716fd0b938 | ||
|
|
893fc4c168 | ||
|
|
6f5cf8506f | ||
|
|
c808cb0a1c | ||
|
|
5f677a86a7 | ||
|
|
11540f8cd9 | ||
|
|
9d6ccdcab1 |
7
.flowconfig
Normal file
7
.flowconfig
Normal file
@@ -0,0 +1,7 @@
|
||||
[ignore]
|
||||
|
||||
[include]
|
||||
|
||||
[libs]
|
||||
|
||||
[options]
|
||||
21
.gitignore
vendored
21
.gitignore
vendored
@@ -17,7 +17,7 @@
|
||||
|
||||
# Ignore object files.
|
||||
*.o
|
||||
build/ripple*.js
|
||||
build/*.js
|
||||
tags
|
||||
bin/rippled
|
||||
Debug/*.*
|
||||
@@ -25,6 +25,7 @@ Release/*.*
|
||||
|
||||
# Ignore locally installed node_modules
|
||||
node_modules
|
||||
!test/node_modules
|
||||
|
||||
# Ignore tmp directory.
|
||||
tmp
|
||||
@@ -42,3 +43,21 @@ test/config.js
|
||||
/lib-cov
|
||||
/src-cov
|
||||
/coverage.html
|
||||
/coverage
|
||||
|
||||
# Ignore IntelliJ files
|
||||
.idea
|
||||
|
||||
# Ignore npm-debug
|
||||
npm-debug.log
|
||||
|
||||
# Ignore dist folder, build for bower
|
||||
dist/
|
||||
|
||||
# Ignore flow output directory
|
||||
out/
|
||||
|
||||
# Ignore perf test cache
|
||||
scripts/cache
|
||||
|
||||
eslintrc
|
||||
|
||||
16
.travis.yml
16
.travis.yml
@@ -1,6 +1,18 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
before_script:
|
||||
- npm install -g eslint
|
||||
- curl 'https://raw.githubusercontent.com/ripple/javascript-style-guide/master/eslintrc' > ./eslintrc
|
||||
- eslint --reset -c ./eslintrc $(git --no-pager diff --name-only --diff-filter=AM --relative $(git merge-base FETCH_HEAD origin/HEAD) FETCH_HEAD | grep "\.js$")
|
||||
script: MOCHA_REPORTER=tap npm test --coverage
|
||||
after_success:
|
||||
- npm run coveralls
|
||||
notifications:
|
||||
email:
|
||||
false
|
||||
email: false
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/d1ec4245f90231619d30
|
||||
on_success: change # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: false # default: false
|
||||
|
||||
103
Gruntfile.js
103
Gruntfile.js
@@ -1,103 +0,0 @@
|
||||
module.exports = function(grunt) {
|
||||
grunt.loadNpmTasks('grunt-webpack');
|
||||
grunt.loadNpmTasks('grunt-dox');
|
||||
grunt.loadNpmTasks('grunt-contrib-concat');
|
||||
grunt.loadNpmTasks('grunt-contrib-watch');
|
||||
|
||||
grunt.initConfig({
|
||||
pkg: grunt.file.readJSON('package.json'),
|
||||
meta: {
|
||||
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
|
||||
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
|
||||
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
|
||||
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
|
||||
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
|
||||
},
|
||||
concat: {
|
||||
sjcl: {
|
||||
src: [
|
||||
"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-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-jacobi.js"
|
||||
],
|
||||
dest: 'build/sjcl.js'
|
||||
}
|
||||
},
|
||||
webpack: {
|
||||
options: {
|
||||
entry: "./src/js/ripple/index.js",
|
||||
output: {
|
||||
library: "ripple"
|
||||
},
|
||||
cache: true
|
||||
},
|
||||
lib: {
|
||||
output: {
|
||||
filename: "build/ripple-<%= pkg.version %>.js"
|
||||
}
|
||||
},
|
||||
lib_debug: {
|
||||
output: {
|
||||
filename: "build/ripple-<%= pkg.version %>-debug.js"
|
||||
},
|
||||
debug: true,
|
||||
devtool: 'eval'
|
||||
},
|
||||
lib_min: {
|
||||
output: {
|
||||
filename: "build/ripple-<%= pkg.version %>-min.js"
|
||||
},
|
||||
optimize: {
|
||||
minimize: true
|
||||
}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
sjcl: {
|
||||
files: ['<%= concat.sjcl.src %>'],
|
||||
tasks: 'concat:sjcl'
|
||||
},
|
||||
lib: {
|
||||
files: 'src/js/ripple/*.js',
|
||||
tasks: 'webpack:lib_debug'
|
||||
}
|
||||
},
|
||||
dox: {
|
||||
libdocs: {
|
||||
options: {
|
||||
title: "Test"
|
||||
},
|
||||
src: ['src/js/ripple/'],
|
||||
dest: 'build/docs'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Tasks
|
||||
grunt.registerTask('default', ['concat:sjcl', 'webpack']);
|
||||
|
||||
};
|
||||
197
Gulpfile.js
Normal file
197
Gulpfile.js
Normal file
@@ -0,0 +1,197 @@
|
||||
'use strict';
|
||||
var gulp = require('gulp');
|
||||
var gutil = require('gulp-util');
|
||||
var watch = require('gulp-watch');
|
||||
var plumber = require('gulp-plumber');
|
||||
var filelog = require('gulp-filelog');
|
||||
var cleanDest = require('gulp-clean-dest');
|
||||
var concat = require('gulp-concat');
|
||||
var uglify = require('gulp-uglify');
|
||||
var rename = require('gulp-rename');
|
||||
var webpack = require('webpack');
|
||||
var bump = require('gulp-bump');
|
||||
var react = require('gulp-react');
|
||||
var flow = require('gulp-flowtype');
|
||||
var argv = require('yargs').argv;
|
||||
// var header = require('gulp-header');
|
||||
|
||||
var pkg = require('./package.json');
|
||||
|
||||
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'
|
||||
];
|
||||
|
||||
function logPluginError(error) {
|
||||
gutil.log(error.toString());
|
||||
}
|
||||
|
||||
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() {
|
||||
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);
|
||||
});
|
||||
|
||||
/**
|
||||
* Generate a WebPack external for a given unavailable module which replaces
|
||||
* that module's constructor with an error-thrower
|
||||
*/
|
||||
|
||||
function buildUseError(cons) {
|
||||
return ('var {<CONS>:function(){throw new Error('
|
||||
+ '"Class is unavailable in this build: <CONS>")}}')
|
||||
.replace(new RegExp('<CONS>', 'g'), cons);
|
||||
}
|
||||
|
||||
gulp.task('build-core', ['concat-sjcl'], function(callback) {
|
||||
webpack({
|
||||
entry: [
|
||||
'./src/js/ripple/remote.js'
|
||||
],
|
||||
externals: [
|
||||
{
|
||||
'./transaction': buildUseError('Transaction'),
|
||||
'./orderbook': buildUseError('OrderBook'),
|
||||
'./account': buildUseError('Account'),
|
||||
'./serializedobject': buildUseError('SerializedObject')
|
||||
}
|
||||
],
|
||||
output: {
|
||||
library: 'ripple',
|
||||
path: './build/',
|
||||
filename: ['ripple-', '-core.js'].join(pkg.version)
|
||||
},
|
||||
plugins: [
|
||||
new webpack.optimize.UglifyJsPlugin()
|
||||
]
|
||||
}, callback);
|
||||
});
|
||||
|
||||
gulp.task('bower-build', ['build'], function() {
|
||||
return gulp.src(['./build/ripple-', '.js'].join(pkg.version))
|
||||
.pipe(rename('ripple.js'))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
});
|
||||
|
||||
gulp.task('bower-build-min', ['build-min'], function() {
|
||||
return gulp.src(['./build/ripple-', '-min.js'].join(pkg.version))
|
||||
.pipe(rename('ripple-min.js'))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
});
|
||||
|
||||
gulp.task('bower-build-debug', ['build-debug'], function() {
|
||||
return gulp.src(['./build/ripple-', '-debug.js'].join(pkg.version))
|
||||
.pipe(rename('ripple-debug.js'))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
});
|
||||
|
||||
gulp.task('bower-version', function() {
|
||||
gulp.src('./dist/bower.json')
|
||||
.pipe(bump({version: pkg.version}))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
});
|
||||
|
||||
gulp.task('bower', ['bower-build', 'bower-build-min', 'bower-build-debug',
|
||||
'bower-version']);
|
||||
|
||||
gulp.task('watch', function() {
|
||||
gulp.watch('src/js/ripple/*', ['build-debug']);
|
||||
});
|
||||
|
||||
// To use this, each javascript file must have /* @flow */ on the first line
|
||||
gulp.task('typecheck', function() {
|
||||
return gulp.src('src/js/ripple/*.js')
|
||||
.pipe(flow({ // note: do not set the 'all' option, it is broken
|
||||
weak: true, // remove this after all errors are addressed
|
||||
killFlow: true
|
||||
}));
|
||||
});
|
||||
|
||||
gulp.task('strip', function() {
|
||||
return gulp.src('src/js/ripple/*.js')
|
||||
.pipe(watch('src/js/ripple/*.js'))
|
||||
.pipe(cleanDest('out')) // delete outdated output file before stripping
|
||||
.pipe(plumber()) // prevent an error in one file from ending build
|
||||
.pipe(react({stripTypes: true}).on('error', logPluginError))
|
||||
.pipe(filelog())
|
||||
.pipe(gulp.dest('out'));
|
||||
});
|
||||
|
||||
gulp.task('version-bump', function() {
|
||||
if (!argv.type) {
|
||||
throw new Error('No type found, pass it in using the --type argument');
|
||||
}
|
||||
|
||||
gulp.src('./package.json')
|
||||
.pipe(bump({type: argv.type}))
|
||||
.pipe(gulp.dest('./'));
|
||||
});
|
||||
|
||||
gulp.task('version-beta', function() {
|
||||
gulp.src('./package.json')
|
||||
.pipe(bump({version: pkg.version + '-beta'}))
|
||||
.pipe(gulp.dest('./'));
|
||||
});
|
||||
|
||||
gulp.task('default', ['concat-sjcl', 'build', 'build-debug', 'build-min']);
|
||||
307
HISTORY.md
307
HISTORY.md
@@ -1,3 +1,310 @@
|
||||
##0.12.1
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
+ [Removed support for parsing native amounts in floating point format](https://github.com/ripple/ripple-lib/commit/e80cd1ff55deae9cd5b0ae85be957f86856b887e)
|
||||
|
||||
|
||||
**Changes**
|
||||
|
||||
+ [Fix taker pays funded calculation](https://github.com/ripple/ripple-lib/commit/5af824f5cf46c7b9caa58ee0a757bf854d26c8dc)
|
||||
|
||||
+ [Fix order funded amount calculation](https://github.com/ripple/ripple-lib/commit/b2cdb1a6aed968b1f306e8dadbd4b7ca37e5aa03)
|
||||
|
||||
+ [Fix handling of quality in order book](https://github.com/ripple/ripple-lib/commit/2a5a8b498da60df738ba18d5c265f34771e8a1af)
|
||||
|
||||
+ [Fix currency parsing of non-alphanumeric and no-currency currencies](https://github.com/ripple/ripple-lib/commit/2166bb2e88eae8d5f1aba77338f69e8a9edf6a6f)
|
||||
|
||||
+ [Add Amount.strict_mode for toggling range validation](https://github.com/ripple/ripple-lib/commit/b5ed8f59a7dab1a17491618b8d9193646c314fb4)
|
||||
|
||||
+ [Add filename and line number to log, use log.warn() for deprecations](https://github.com/ripple/ripple-lib/commit/90329d3d73f1a76675063655b407513e32dc048b)
|
||||
|
||||
+ [Fix handling of falsy parameters in requestLedger](https://github.com/ripple/ripple-lib/commit/6023efed41b7812b3bab660a1c0dc9f0a21000b9)
|
||||
|
||||
+ [Refactor base conversion](https://github.com/ripple/ripple-lib/commit/f2b63fa4a80663eb29472bc6bb1aea8159f1f205)
|
||||
|
||||
+ [Update binary transaction format](https://github.com/ripple/ripple-lib/commit/8e134918fb4c22983320a3102f955e4568bb1dfb)
|
||||
|
||||
+ [Add DefaultRipple account flag](https://github.com/ripple/ripple-lib/commit/3e249902c4cf25b4da5e75048c84ae391be83b10)
|
||||
|
||||
+ [Remove `Features` field requirement in `SetFee` transaction format](https://github.com/ripple/ripple-lib/commit/a20a649013646710c078d4ce1e210f87c7fe74fe)
|
||||
|
||||
+ [Remove `RegularKey` field requirement in `SetRegularKey` transaction format](https://github.com/ripple/ripple-lib/commit/c275174f27877ba8f389eb4efe969feb514d6e46)
|
||||
|
||||
|
||||
##0.12.0
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
+ REMOVED Remote storage interface
|
||||
+ REMOVED Remote `ping` configuration
|
||||
+ REMOVED Old/deprecated Remote server configuration (websocket_ip, websocket_port)
|
||||
+ REMOVED browser `online` reconnect listener
|
||||
- [Cleanup, deprecations - 2833a7b6](https://github.com/ripple/ripple-lib/commit/2833a7b66e696dab427464625077f9b93092d0d5)
|
||||
|
||||
+ Remove `jsbn` and use `bignumber.js` instead for big number math
|
||||
+ The `allow_nan` flag has been removed. Results for invalid amounts will always be `NaN`
|
||||
- [Refactor to use bignumber.js - d025b4a0](https://github.com/ripple/ripple-lib/commit/d025b4a0c3a98a6de27a1bee9573c85347bcd66b)
|
||||
- [Handle invalid input in parse_human - c8f18c8c](https://github.com/ripple/ripple-lib/commit/c8f18c8c8590b7b48e370e0325b6677b7720294f)
|
||||
- [Check for null in isNumber - b86790c8](https://github.com/ripple/ripple-lib/commit/b86790c8543c239a532fd7697d4652829019d385)
|
||||
- [Cleanup amount.js - d0fb291c](https://github.com/ripple/ripple-lib/commit/d0fb291c4e330193a244902156f1d74730da357d)
|
||||
|
||||
|
||||
**Changes**
|
||||
|
||||
+ [Add deprecation warnings to request constructors. The first argument to request constructor functions should be an object containing request properties](https://github.com/ripple/ripple-lib/commit/35d76b3520934285f80059c1badd6c522539104c)
|
||||
|
||||
+ [Fix taker_gets_funded exceeding offer.TakerGets](https://github.com/ripple/ripple-lib/commit/b19ecb4482b589d575382b7a5d0480b963383bb1)
|
||||
|
||||
+ [Fix unsymmetric memo serializing](https://github.com/ripple/ripple-lib/commit/1ed36fabdbd54f4d31078c2b0eaa3becc0fe2821)
|
||||
|
||||
+ [Fix IOU value passed to `Amount.from_json()`](https://github.com/ripple/ripple-lib/commit/fd1b64393dffb3d1819cd40b8d43df43a4db042d)
|
||||
|
||||
+ [Update transaction binary parsing to account for XRP delivered amounts](https://github.com/ripple/ripple-lib/commit/35a346a674e6ee1e1e495db93700d55984efc7dd)
|
||||
|
||||
+ [Bumped dependencies](https://github.com/ripple/ripple-lib/commit/f9bc7cc746b44b24b61bbe260ae2e9d9617286da)
|
||||
|
||||
|
||||
|
||||
##0.11.0
|
||||
|
||||
+ [Track the funded status of an order based on cumulative account orders](https://github.com/ripple/ripple-lib/commit/67d39737a4d5e0fcd9d9b47b9083ee00e5a9e652) and [67d3973](https://github.com/ripple/ripple-lib/commit/b6b99dde022e1e14c4797e454b1d7fca50e49482)
|
||||
|
||||
+ Remove blobvault client from ripple-lib, use the [`ripple-vault-client`](https://github.com/ripple/ripple-vault-client) instead [9b3d62b7](https://github.com/ripple/ripple-lib/commit/9b3d62b765c4c25beae6eb0fa57ef3a07f2581b1)
|
||||
|
||||
+ [Add support for `ledger` option in requestBookOffers](https://github.com/ripple/ripple-lib/commit/34c0677c453c409ef0a5b351959abdc176d3bacb)
|
||||
|
||||
+ [Add support for `limit` option in requestBookOffers](https://github.com/ripple/ripple-lib/commit/d1d4452217c878d0b377d24830b4cd8b3162f6e0)
|
||||
|
||||
+ [Add `ledgerSelect` request constructor in `Remote`](https://github.com/ripple/ripple-lib/commit/98f40abfc3aa74dec5067a2d90002756cc8acd01)
|
||||
|
||||
+ [Default to binary data for commands that accept the binary flag](https://github.com/ripple/ripple-lib/commit/7cb113fcbcfc1e3e9830a999148b3e78df3387cc)
|
||||
|
||||
+ [Fix metadata account check](https://github.com/ripple/ripple-lib/commit/3f61598d6c87e3cc877af60e2d515f9eff73dfe1)
|
||||
|
||||
+ [Double check `tes` code before emitting `success`](https://github.com/ripple/ripple-lib/commit/97a8c874903eb7309d8f755955ac80872f670582)
|
||||
|
||||
+ [Decrease redundancy in binary account_tx parsing](https://github.com/ripple/ripple-lib/commit/0aba638e6e7f4f6e22cb6424eed3897ebad90a5a)
|
||||
|
||||
+ [Abort server connection on unrecoverable TLS error](https://github.com/ripple/ripple-lib/commit/000a2ea00c57157044aeca0fb3f24b37669b163c)
|
||||
|
||||
+ [Fix complete ledgers check on subscription that is not initial](https://github.com/ripple/ripple-lib/commit/89de91301e682a46dc60aaacc7ae152e8fe1b7c7)
|
||||
|
||||
|
||||
##0.10.0
|
||||
|
||||
+ [Transaction changes](https://github.com/ripple/ripple-lib/pull/221)
|
||||
|
||||
+ **Important** `tef*` and `tel*` and errors will no longer be presented as
|
||||
final. Rather than considering these errors final, ripple-lib will wait until
|
||||
the `LastLedgerSequence` specified in the transaction is exceeded. This makes
|
||||
failures more definitive, and ensures that no transaction will resubmit
|
||||
indefinitely.
|
||||
|
||||
+ A new, final tej-class error is introduced to account for transactions that
|
||||
are locally determined to have expired: `tejMaxLedger`.
|
||||
|
||||
+ [Allow per transaction fees to be set, `transaction.setFixedFee()`](https://github.com/ripple/ripple-lib/commit/9b22f279bcbe60ee6bcf4b7fa60a48e9c197a828)
|
||||
|
||||
+ [Improve memo support](https://github.com/ripple/ripple-lib/commit/1704ac4ae144c0ce54afad86f644c75a632080b1)
|
||||
- Add `MemoFormat` property for memo
|
||||
- Enforce `MemoFormat` and `MemoType` to be valid ASCII
|
||||
- Support `text` and `json` MemoFormat
|
||||
|
||||
+ [Update jscl library](https://github.com/ripple/ripple-lib/commit/3204998fcb6f31d6c90532a737a4adb8a1e420f6)
|
||||
- Improved entropy by taking advantage of platform crypto
|
||||
- Use jscl's k256 curve instead of altering the c256 curve with k256 configuration
|
||||
- **deprecated:** the c256 curve is linked to the k256 curve to provide backwards compatibility, this link will be removed in the future
|
||||
|
||||
+ [Fix empty queue check on reconnect](https://github.com/ripple/ripple-lib/commit/3c21994adcf72d1fbd87d453ceb917f9ad6df4ec)
|
||||
|
||||
##0.9.4
|
||||
|
||||
+ [Normalize offers from book_offers and transaction stream](https://github.com/ripple/ripple-lib/commit/86ed24b94cf7c8929c87db3a63e9bbea7f767e9c)
|
||||
|
||||
+ [Fix: Amount.to_human() precision rounding](https://github.com/ripple/ripple-lib/commit/e371cc2c3ceccb3c1cfdf18b98d80093147dd8b2)
|
||||
|
||||
+ [Fix: fractional drops in funded taker_pays setter](https://github.com/ripple/ripple-lib/commit/0d7fc0a573a144caac15dd13798b23eeb1f95fb4)
|
||||
|
||||
##0.9.3
|
||||
|
||||
+ [Change `presubmit` to emit immediately before transaction submit](https://github.com/ripple/ripple-lib/commit/7a1feaa89701bf861ab31ebd8ffdc8d8d1474e29)
|
||||
|
||||
+ [Add a "core" browser build of ripple-lib which has a subset of features and smaller file size](https://github.com/ripple/ripple-lib/pull/205)
|
||||
|
||||
+ [Update binformat with missing fields from rippled](https://github.com/ripple/ripple-lib/commit/cae980788efb00191bfd0988ed836d60cdf7a9a2)
|
||||
|
||||
+ [Wait for transaction validation before returning `tec` error](https://github.com/ripple/ripple-lib/commit/6bdd4b2670906588852fc4dda457607b4aac08e4)
|
||||
|
||||
+ [Change default `max_fee` on `Remote` to `1 XRP`](https://github.com/ripple/ripple-lib/commit/d6b1728c23ff85c3cc791bed6982a750641fd95f)
|
||||
|
||||
+ [Fix: Request ledger_accept should return the Remote](https://github.com/ripple/ripple-lib/pull/209)
|
||||
|
||||
##0.9.2
|
||||
|
||||
+ [**Breaking change**: Change accountRequest method signature](https://github.com/ripple/ripple-lib/commit/6f5d1104aa3eb440c518ec4f39e264fdce15fa15)
|
||||
|
||||
+ [Add paging behavior for account requests, `account_lines` and `account_offers`](https://github.com/ripple/ripple-lib/commit/722f4e175dbbf378e51b49142d0285f87acb22d7)
|
||||
|
||||
+ [Add max_fee setter to transactions to set max fee the submitter is willing to pay] (https://github.com/ripple/ripple-lib/commit/24587fab9c8ad3840d7aa345a7037b48839e09d7)
|
||||
|
||||
+ [Fix: cap IOU Amounts to their max and min value] (https://github.com/ripple/ripple-lib/commit/f05941fbc46fdb7c6fe7ad72927af02d527ffeed)
|
||||
|
||||
Example on how to use paging with `account_offers`:
|
||||
```
|
||||
// A valid `ledger_index` or `ledger_hash` is required to provide a reliable result.
|
||||
// Results can change between ledger closes, so the provided ledger will be used as base.
|
||||
var options = {
|
||||
account: < rippleAccount >,
|
||||
limit: < Number between 10 and 400 >,
|
||||
ledger: < valid ledger_index or ledger_hash >
|
||||
}
|
||||
|
||||
// The `marker` comes back in an account request if there are more results than are returned
|
||||
// in the current response. The amount of results per response are determined by the `limit`.
|
||||
if (marker) {
|
||||
options.marker = < marker >;
|
||||
}
|
||||
|
||||
var request = remote.requestAccountOffers(options);
|
||||
```
|
||||
|
||||
[Full working example](https://github.com/geertweening/ripple-lib-scripts/blob/master/account_offers_paging.js)
|
||||
|
||||
|
||||
##0.9.1
|
||||
|
||||
+ Switch account requests to use ledgerSelect rather than ledgerChoose ([278df90](https://github.com/ripple/ripple-lib/commit/278df9025a20228de22379a53c76ca12d40fa591))
|
||||
|
||||
+ **Deprecated** setting `ident` and `account_index` on account requests ([278df90](https://github.com/ripple/ripple-lib/commit/278df9025a20228de22379a53c76ca12d40fa591))
|
||||
|
||||
+ Change initial account transaction sequence to 1 ([a3c1d06](https://github.com/ripple/ripple-lib/commit/a3c1d06eba883dc84fe2bfe700e4309795c84cac))
|
||||
|
||||
+ Fix: instance transaction withoute remote ([d3b6b81](https://github.com/ripple/ripple-lib/commit/d3b6b8127c7b01e416b400c25abf1719bdd008ca))
|
||||
|
||||
+ Fix: account root request ledger argument ([bc1f9f8](https://github.com/ripple/ripple-lib/commit/bc1f9f8a286b187d36ebaf552694e31e73742293))
|
||||
|
||||
+ Fix: rsign.js local signing and example ([d3b6b81](https://github.com/ripple/ripple-lib/commit/d3b6b8127c7b01e416b400c25abf1719bdd008ca) and [f1004c6](https://github.com/ripple/ripple-lib/commit/f1004c6db2a0ce59bbabbb8f2b355a9fd9995fd8))
|
||||
|
||||
|
||||
##0.9.0
|
||||
|
||||
+ Add routes to the vault client for KYC attestations ([ed2da574](https://github.com/ripple/ripple-lib/commit/ed2da57475acf5e9d2cf3373858f4274832bd83f))
|
||||
|
||||
+ Currency: add `show_interest` flag to show or hide interest in `Currency.to_human()` and `Currency.to_json()` [Example use in tests](https://github.com/ripple/ripple-lib/blob/947ec3edc2e7c8f1ef097e496bf552c74366e749/test/currency-test.js#L123)
|
||||
|
||||
+ Configurable maxAttempts for transaction submission ([d107092](https://github.com/ripple/ripple-lib/commit/d10709254061e9e4416d2cb78b5cac1ec0d7ffa5))
|
||||
|
||||
+ Binformat: added missing TransactionResult options ([6abed8d](https://github.com/ripple/ripple-lib/commit/6abed8dd5311765b2eb70505dadbdf5121439ca8))
|
||||
|
||||
+ **Breaking change:** make maxLoops in seed.get_key optional. [Example use in tests](https://github.com/ripple/ripple-lib/blob/23e473b6886c457781949c825b3ff48b3984e51f/test/seed-test.js) ([23e473b](https://github.com/ripple/ripple-lib/commit/23e473b6886c457781949c825b3ff48b3984e51f))
|
||||
|
||||
+ Shrinkwrap packages for dependency locking ([2dcd5f9](2dcd5f94fbc71200eb08a5044c76ef94f7971913))
|
||||
|
||||
+ Fix: Amount.to_human() precision bugs ([4be209e](https://github.com/ripple/ripple-lib/commit/4be209e286b5b209bec7bcd1212098985e15ff2f) and [7708c64](https://github.com/ripple/ripple-lib/commit/7708c64576e70ce3ac190442daceb30e4446aab7))
|
||||
|
||||
+ Fix: change handling of requestLedger options ([57b7030](https://github.com/ripple/ripple-lib/commit/57b70300f5f0c7534ede118ddbb5d8762668a4f8))
|
||||
|
||||
|
||||
##0.8.2
|
||||
|
||||
+ Currency: Allow mixed letters and numbers in currencies
|
||||
|
||||
+ Deprecate account_tx map/reduce/filterg
|
||||
|
||||
+ Fix: correct requestLedger arguments
|
||||
|
||||
+ Fix: missing subscription on error events for some server methods
|
||||
|
||||
+ Fix: orderbook reset on reconnect
|
||||
|
||||
+ Fix: ripple-lib crashing. Add potential missing error handlers
|
||||
|
||||
|
||||
##0.8.1
|
||||
|
||||
+ Wallet: Add Wallet class that generates wallets
|
||||
|
||||
+ Make npm test runnable in Windows.
|
||||
|
||||
+ Fix several stability issues, see merged PR's for details
|
||||
|
||||
+ Fix bug in Amount.to_human_full()
|
||||
|
||||
+ Fix undefined fee states when connecting to a rippled that is syncing
|
||||
|
||||
|
||||
##0.8.0
|
||||
|
||||
+ Orderbook: Added tracking of offer funds for determining when offers are not funded
|
||||
|
||||
+ Orderbook: Added tests
|
||||
|
||||
+ Orderbook: Update owner funds
|
||||
|
||||
+ Transactions: If transaction errs with `tefALREADY`, wait until all possible submissions err with the same before emitting `error`. Fixes a client "Transaction malformed" bug.
|
||||
|
||||
+ Transactions: Track submissions, don't bother submitting to unconnected servers
|
||||
|
||||
+ Request: `request.request()` now accepts an array of servers as first argument. Servers can be represented with URL, or the server object itself.
|
||||
|
||||
+ Request: `request.broadcast()` now returns the number of servers request was sent to
|
||||
|
||||
+ Server: Acquire host information from server without additional request
|
||||
|
||||
+ Amount: Add a constant for the maximum canonical value that can be expressed as a Ripple value
|
||||
|
||||
+ Amount: Make Constants static fields on the class, instead of a seperate export
|
||||
|
||||
|
||||
##0.7.39
|
||||
|
||||
+ Improvements to multi-server support. Fixed an issue where a server's score was not reset and connections would keep dropping after being connected for a significant amount of time.
|
||||
|
||||
+ Improvements in order book support. Added support for currency pairs with interest bearing currencies. You can request an order book with hex, ISO code or full name for the currency.
|
||||
|
||||
+ Fix value parsing for amount/currency order pairs, e.g. `Amount.from_human("XAU 12345.6789")`
|
||||
|
||||
+ Improved Amount parsing from human readable string given a hex currency, e.g. `Amount.from_human("10 015841551A748AD2C1F76FF6ECB0CCCD00000000")`
|
||||
|
||||
+ Improvements to username normalization in the vault client
|
||||
|
||||
+ Add 2-factor authentication support for vault client
|
||||
|
||||
+ Removed vestiges of Grunt, switched to Gulp
|
||||
|
||||
|
||||
##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
|
||||
|
||||
|
||||
12
Makefile
12
Makefile
@@ -1,12 +0,0 @@
|
||||
test:
|
||||
mocha --reporter spec test/*-test.js
|
||||
|
||||
coverage:
|
||||
rm -rf src-cov
|
||||
mkdir src-cov
|
||||
mkdir src-cov/js
|
||||
jscoverage --no-highlight src/js/ripple src-cov/js/ripple
|
||||
RIPPLE_LIB_COV=1 mocha --reporter html-cov test/*-test.js > coverage.html
|
||||
rm -rf src-cov
|
||||
|
||||
.PHONY: test
|
||||
91
README.md
91
README.md
@@ -1,33 +1,36 @@
|
||||
#The Ripple JavaScript Library
|
||||
#ripple-lib
|
||||
|
||||
`ripple-lib` connects to the Ripple network via the WebSocket protocol and runs in Node.js as well as in the browser.
|
||||
A JavaScript API for interacting with Ripple in Node.js and the browser
|
||||
|
||||
**Use ripple-lib for**
|
||||
[](https://travis-ci.org/ripple/ripple-lib) [](https://coveralls.io/r/ripple/ripple-lib?branch=develop)
|
||||
|
||||
+ 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
|
||||
[](https://www.npmjs.org/package/ripple-lib)
|
||||
|
||||
###In this file:
|
||||
###Features
|
||||
|
||||
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)
|
||||
+ Connect to a rippled server in JavaScript (Node.js or browser)
|
||||
+ Issue [rippled API](https://ripple.com/build/rippled-apis/) requests
|
||||
+ Listen to events on the Ripple network (transaction, ledger, etc.)
|
||||
+ Sign and submit transactions to the Ripple network
|
||||
|
||||
###For additional documentation see:
|
||||
###In this file
|
||||
|
||||
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
|
||||
1. [Installation](#installation)
|
||||
2. [Quick start](#quick-start)
|
||||
3. [Running tests](#running-tests)
|
||||
|
||||
###Also see:
|
||||
###Additional documentation
|
||||
|
||||
+ https://ripple.com/wiki
|
||||
+ https://ripple.com
|
||||
1. [Guides](docs/GUIDES.md)
|
||||
2. [API Reference](docs/REFERENCE.md)
|
||||
3. [Wiki](https://ripple.com/wiki/Ripple_JavaScript_library)
|
||||
|
||||
##Getting `ripple-lib`
|
||||
###Also see
|
||||
|
||||
+ [The Ripple wiki](https://ripple.com/wiki)
|
||||
+ [ripple.com](https://ripple.com)
|
||||
|
||||
##Installation
|
||||
|
||||
**Via npm for Node.js**
|
||||
|
||||
@@ -35,19 +38,34 @@
|
||||
$ npm install ripple-lib
|
||||
```
|
||||
|
||||
**Build from the source using `grunt`**
|
||||
**Via bower (for browser use)**
|
||||
|
||||
```
|
||||
$ bower install ripple
|
||||
```
|
||||
|
||||
See the [bower-ripple repo](https://github.com/ripple/bower-ripple) for additional bower instructions
|
||||
|
||||
|
||||
**Building ripple-lib for browser environments**
|
||||
|
||||
ripple-lib uses Gulp to generate browser builds. These steps will generate minified and non-minified builds of ripple-lib in the `build/` directory.
|
||||
|
||||
```
|
||||
$ git clone https://github.com/ripple/ripple-lib
|
||||
$ npm install
|
||||
$ grunt
|
||||
$ npm run build
|
||||
```
|
||||
|
||||
Then use the minified `build/ripple-*-min.js` in your webpage
|
||||
**Restricted browser builds**
|
||||
|
||||
##Quickstart
|
||||
You may generate browser builds that contain a subset of features. To do this, run `./node_modules/.bin/gulp build-<name>`
|
||||
|
||||
`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:
|
||||
+ `build-core` Contains the functionality to make requests and listen for events such as `ledgerClose`. Only `ripple.Remote` is currently exposed. Advanced features like transaction submission and orderbook tracking are excluded from this build.
|
||||
|
||||
##Quick start
|
||||
|
||||
`Remote.js` ([remote.js](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/remote.js)) is the point of entry for interacting with rippled
|
||||
|
||||
```js
|
||||
/* Loading ripple-lib with Node.js */
|
||||
@@ -58,36 +76,25 @@ var Remote = require('ripple-lib').Remote;
|
||||
|
||||
var remote = new Remote({
|
||||
// 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
|
||||
}
|
||||
]
|
||||
servers: [ 'wss://s1.ripple.com:443' ]
|
||||
});
|
||||
|
||||
remote.connect(function() {
|
||||
/* remote connected */
|
||||
|
||||
// see the API Reference for available functions
|
||||
remote.requestServerInfo(function(err, info) {
|
||||
// process err and info
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
##Running tests
|
||||
|
||||
1. Clone the repository
|
||||
|
||||
2. `cd` into the repository and install dependencies with `npm install`
|
||||
|
||||
3. `npm test` or `make test` or `node_modules\.bin\mocha test\*-test.js`
|
||||
3. `npm test`
|
||||
|
||||
**Generating code coverage**
|
||||
|
||||
ripple-lib uses `jscoverage` to generate code coverage. To generate a file `coverage.html`, run `make coverage`
|
||||
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/`.
|
||||
|
||||
@@ -56,7 +56,7 @@ function ready() {
|
||||
function print_usage() {
|
||||
console.log(
|
||||
'Usage: rsign.js <secret> <json>\n\n',
|
||||
'Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC',
|
||||
'Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC','\''+
|
||||
JSON.stringify({
|
||||
TransactionType: 'Payment',
|
||||
Account: 'r3P9vH81KBayazSTrQj6S25jW6kDb779Gi',
|
||||
@@ -64,7 +64,7 @@ function print_usage() {
|
||||
Amount: '200000000',
|
||||
Fee: '10',
|
||||
Sequence: 1
|
||||
})
|
||||
})+'\''
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
4125
build/sjcl.js
4125
build/sjcl.js
File diff suppressed because it is too large
Load Diff
20
docs/BUILD.md
Normal file
20
docs/BUILD.md
Normal file
@@ -0,0 +1,20 @@
|
||||
Using Flow typechecking
|
||||
=======================
|
||||
|
||||
Stage 1
|
||||
-------
|
||||
1. Add /* @flow */ to the top of a file you want to typecheck
|
||||
2. Run `gulp typecheck` to generate a list of warnings
|
||||
|
||||
Stage 2
|
||||
-------
|
||||
When all source files have the /* @flow */ header and all warnings have been
|
||||
addressed, remove the `weak: true` option from Gulpfile.js, run
|
||||
`gulp typecheck` and remove all the additional warnings.
|
||||
|
||||
Stage 3
|
||||
-------
|
||||
Add type annotations to the source code and run `gulp strip` to strip
|
||||
the type annotations and write the output to the `out` directory. After
|
||||
type annotations are added, the program must be run from the `out` directory
|
||||
because Node does not understand the annotations
|
||||
223
docs/GUIDES.md
223
docs/GUIDES.md
@@ -1,26 +1,25 @@
|
||||
#`ripple-lib` Guides
|
||||
#Guides
|
||||
|
||||
This file provides step-by-step walkthroughs for some of the most common usages of `ripple-lib`.
|
||||
|
||||
###Guides in this document:
|
||||
###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)
|
||||
1. [Connecting to the Ripple network with `Remote`](GUIDES.md#connecting-to-the-ripple-network)
|
||||
2. [Using `Remote` functions and `Request` objects](GUIDES.md#sending-rippled-API-requests)
|
||||
3. [Listening to the network](GUIDES.md#listening-to-the-network)
|
||||
4. [Submitting a payment to the network](GUIDES.md#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)
|
||||
5. [Submitting a trade offer to the network](GUIDES.md#submitting-a-trade-offer-to-the-network)
|
||||
|
||||
###Also see
|
||||
|
||||
###Also see:
|
||||
1. [The ripple-lib README](../README.md)
|
||||
2. [The ripple-lib API Reference](REFERENCE.md)
|
||||
|
||||
1. [The `ripple-lib` README](../README.md)
|
||||
2. [The `ripple-lib` API Reference](REFERENCE.md)
|
||||
##Connecting to the Ripple network
|
||||
|
||||
##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:
|
||||
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;
|
||||
@@ -30,39 +29,80 @@ This file provides step-by-step walkthroughs for some of the most common usages
|
||||
```
|
||||
3. Create a new `Remote` and connect to the network:
|
||||
```js
|
||||
var remote = new Remote({options});
|
||||
|
||||
remote.connect(function() {
|
||||
var options = {
|
||||
trace : false,
|
||||
trusted: true,
|
||||
local_signing: true,
|
||||
servers: [
|
||||
{ host: 's-west.ripple.com', port: 443, secure: true }
|
||||
]
|
||||
}
|
||||
|
||||
var remote = new Remote(options);
|
||||
|
||||
remote.connect(function(err, res) {
|
||||
/* 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.
|
||||
|
||||
##Generating a new Ripple Wallet
|
||||
|
||||
##2. Using `Remote` functions and `Request` objects
|
||||
```js
|
||||
var ripple = require('ripple-lib');
|
||||
|
||||
All `Remote` functions return a `Request` object.
|
||||
// subscribing to a server allows for more entropy
|
||||
var remote = new ripple.Remote({
|
||||
servers: [
|
||||
{ host: 's1.ripple.com', port: 443, secure: true }
|
||||
]
|
||||
});
|
||||
|
||||
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.
|
||||
remote.connect(function(err, res) {
|
||||
/* remote connected */
|
||||
});
|
||||
|
||||
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):
|
||||
// Wait for randomness to have been added.
|
||||
// The entropy of the random generator is increased
|
||||
// by random data received from a rippled
|
||||
remote.once('random', function(err, info) {
|
||||
var wallet = ripple.Wallet.generate();
|
||||
console.log(wallet);
|
||||
// { address: 'rEf4sbVobiiDGExrNj2PkNHGMA8eS6jWh3',
|
||||
// secret: 'shFh4a38EZpEdZxrLifEnVPAoBRce' }
|
||||
});
|
||||
```
|
||||
|
||||
+ Using a `Remote` function with `Request` event listeners:
|
||||
|
||||
##Sending rippled API requests
|
||||
|
||||
`Remote` contains functions for constructing a `Request` object.
|
||||
|
||||
A `Request` is an `EventEmitter` so you can listen for success or failure events -- or, instead, you can provide a callback.
|
||||
|
||||
Here is an example, using [requestServerInfo](https://ripple.com/wiki/JSON_Messages#server_info).
|
||||
|
||||
+ Constructing a `Request` with event listeners
|
||||
```js
|
||||
var request = remote.request_server_info();
|
||||
request.on('success', function(res) {
|
||||
var request = remote.requestServerInfo();
|
||||
|
||||
request.on('success', function onSuccess(res) {
|
||||
//handle success
|
||||
});
|
||||
request.on('error', function(err) {
|
||||
|
||||
request.on('error', function onError(err) {
|
||||
//handle error
|
||||
});
|
||||
request.request(); // this triggers the request if it has not already been sent to the server
|
||||
|
||||
request.request();
|
||||
```
|
||||
|
||||
+ Using a `Remote` function with a callback:
|
||||
+ Using a callback:
|
||||
```js
|
||||
remote.request_server_info(function(err, res) {
|
||||
remote.request('server_info', function(err, res) {
|
||||
if (err) {
|
||||
//handle error
|
||||
} else {
|
||||
@@ -74,14 +114,69 @@ remote.request_server_info(function(err, res) {
|
||||
__NOTE:__ See the API Reference for available [`Remote` functions](REFERENCE.md#2-remote-functions)
|
||||
|
||||
|
||||
##Listening to the network
|
||||
|
||||
See the [wiki](https://ripple.com/wiki/JSON_Messages#subscribe) for details on subscription requests.
|
||||
|
||||
```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() {
|
||||
var remote = new Remote({
|
||||
// see the API Reference for available options
|
||||
servers: [ 'wss://s1.ripple.com:443' ]
|
||||
});
|
||||
|
||||
remote.connect(function() {
|
||||
console.log('Remote connected');
|
||||
|
||||
var streams = [
|
||||
'ledger',
|
||||
'transactions'
|
||||
];
|
||||
|
||||
var request = remote.requestSubscribe(streams);
|
||||
|
||||
request.on('error', function(error) {
|
||||
console.log('request error: ', error);
|
||||
});
|
||||
|
||||
|
||||
##3. Submitting a payment to the network
|
||||
// the `ledger_closed` and `transaction` will come in on the remote
|
||||
// since the request for subscribe is finalized after the success return
|
||||
// the streaming events will still come in, but not on the initial request
|
||||
remote.on('ledger_closed', function(ledger) {
|
||||
console.log('ledger_closed: ', JSON.stringify(ledger, null, 2));
|
||||
});
|
||||
|
||||
remote.on('transaction', function(transaction) {
|
||||
console.log('transaction: ', JSON.stringify(transaction, null, 2));
|
||||
});
|
||||
|
||||
remote.on('error', function(error) {
|
||||
console.log('remote error: ', error);
|
||||
});
|
||||
|
||||
// fire the request
|
||||
request.request();
|
||||
});
|
||||
});
|
||||
```
|
||||
* https://ripple.com/wiki/RPC_API#transactions_stream_messages
|
||||
* https://ripple.com/wiki/RPC_API#ledger_stream_messages
|
||||
|
||||
##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 */
|
||||
/* Loading ripple-lib Remote and Amount modules in Node.js */
|
||||
var Remote = require('ripple-lib').Remote;
|
||||
var Amount = require('ripple-lib').Amount;
|
||||
|
||||
@@ -97,13 +192,11 @@ var AMOUNT = Amount.from_human('1XRP');
|
||||
var remote = new Remote({ /* Remote options */ });
|
||||
|
||||
remote.connect(function() {
|
||||
remote.set_secret(MY_ADDRESS, MY_SECRET);
|
||||
remote.setSecret(MY_ADDRESS, MY_SECRET);
|
||||
|
||||
var transaction = remote.transaction();
|
||||
|
||||
transaction.payment({
|
||||
from: MY_ADDRESS,
|
||||
to: RECIPIENT,
|
||||
var transaction = remote.createTransaction('Payment', {
|
||||
account: MY_ADDRESS,
|
||||
destination: RECIPIENT,
|
||||
amount: AMOUNT
|
||||
});
|
||||
|
||||
@@ -124,12 +217,12 @@ Since the fee required for a transaction may change between the time when the or
|
||||
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
|
||||
|
||||
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:
|
||||
Submitting a trade offer to the network is similar to submitting a payment transaction. Here is an example offering to sell 1 USD in exchange for 100 XRP:
|
||||
|
||||
```js
|
||||
/* Loading ripple-lib Remote and Amount modules in Node.js */
|
||||
/* Loading ripple-lib Remote and Amount modules in Node.js */
|
||||
var Remote = require('ripple-lib').Remote;
|
||||
var Amount = require('ripple-lib').Amount;
|
||||
|
||||
@@ -139,27 +232,17 @@ var Amount = require('ripple-lib').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 GATEWAY = 'rrrGateWay';
|
||||
|
||||
var remote = new Remote({ /* Remote options */ });
|
||||
|
||||
remote.connect(function() {
|
||||
remote.set_secret(MY_ADDRESS, MY_SECRET);
|
||||
remote.setSecret(MY_ADDRESS, MY_SECRET);
|
||||
|
||||
var transaction = remote.transaction();
|
||||
|
||||
transaction.offer_create({
|
||||
from: MY_ADDRESS,
|
||||
buy: BUY_AMOUNT,
|
||||
sell: SELL_AMOUNT,
|
||||
expiration: EXPIRATION
|
||||
var transaction = remote.createTransaction('OfferCreate', {
|
||||
account: MY_ADDRESS,
|
||||
taker_pays: '100',
|
||||
taker_gets: '1/USD/' + GATEWAY
|
||||
});
|
||||
|
||||
transaction.submit(function(err, res) {
|
||||
@@ -167,35 +250,3 @@ remote.connect(function() {
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
##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
|
||||
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
#`ripple-lib` API Reference
|
||||
#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)
|
||||
|
||||
1. [`Remote` options](REFERENCE.md#remote-options)
|
||||
2. [`Request` constructors](REFERENCE.md#request-constructor-functions)
|
||||
+ [Server requests](REFERENCE.md#server-requests)
|
||||
+ [Ledger requests](REFERENCE.md#ledger-requests)
|
||||
+ [Transaction requests](REFERENCE.md#transaction-requests)
|
||||
+ [Account requests](REFERENCE.md#account-requests)
|
||||
+ [Orderbook requests](REFERENCE.md#orderbook-requests)
|
||||
+ [Transaction requests](REFERENCE.md#transaction-requests)
|
||||
3. [`Transaction` constructors](REFERENCE.md#transaction-constructors)
|
||||
+ [Transaction events](REFERENCE.md#transaction-events)
|
||||
|
||||
###Also see:
|
||||
|
||||
1. [The `ripple-lib` README](../README.md)
|
||||
2. [The `ripple-lib` GUIDES](GUIDES.md)
|
||||
1. [The ripple-lib README](../README.md)
|
||||
2. [The ripple-lib GUIDES](GUIDES.md)a
|
||||
|
||||
|
||||
#1. `Remote` options
|
||||
#Remote options
|
||||
|
||||
```js
|
||||
/* Loading ripple-lib with Node.js */
|
||||
@@ -31,102 +29,116 @@ var Remote = require('ripple-lib').Remote;
|
||||
/* Loading ripple-lib in a webpage */
|
||||
// var Remote = ripple.Remote;
|
||||
|
||||
var remote = new Remote({options});
|
||||
var options = { };
|
||||
|
||||
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:
|
||||
+ `trace` *boolean default: false* Log all of the events emitted
|
||||
+ `max_listeners` *number default: 0* Set maxListeners for servers
|
||||
+ `trusted` *boolean default: false*, if remote is trusted (boolean)
|
||||
+ `local_signing` *boolean default: true*
|
||||
+ `local_fee` *boolean default: true* Set whether the transaction fee range will be set locally, see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees))
|
||||
+ `fee_cushion` *number default: 1.2* Extra fee multiplier to account for async fee changes, see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees))
|
||||
+ `max_fee` *number default: Infinity* Maximum acceptable transaction fee, see [A note on transaction fees](GUIDES.md#a-note-on-transaction-fees)
|
||||
+ `servers` *array* Array of server objects of the following form:
|
||||
|
||||
```js
|
||||
{
|
||||
host: <string>
|
||||
, port: <number>
|
||||
, secure: <boolean>
|
||||
{
|
||||
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:
|
||||
or
|
||||
|
||||
```js
|
||||
var request = remote.request_server_info();
|
||||
request.set_server('my.hostname');
|
||||
request.callback(function(err, res) {
|
||||
|
||||
});
|
||||
request.request();
|
||||
'wss://host:port'
|
||||
```
|
||||
|
||||
**[request_unl_list([callback])](https://ripple.com/wiki/RPC_API#unl_list)**
|
||||
#Request constructor functions
|
||||
|
||||
**[request_unl_add(addr, comment, [callback])](https://ripple.com/wiki/RPC_API#unl_add)**
|
||||
Some requests have helper methods to construct the requests object and set properties on the message object. These will often be the more used requests and the helper methods is the preferred way of constructing these requests.
|
||||
Other request can still be made, but the type will have to be passed in directly to request constructor. See examples below.
|
||||
|
||||
**[request_unl_delete(node, [callback])](https://ripple.com/wiki/RPC_API#unl_delete)**
|
||||
If the method is camelCased and starts with `request`, it's a helper method that wraps the request constructor.
|
||||
|
||||
**[request_peers([callback])](https://ripple.com/wiki/RPC_API#peers)**
|
||||
##Server requests
|
||||
|
||||
**[requestServerInfo([callback])](https://ripple.com/wiki/JSON_Messages#server_info)**
|
||||
|
||||
**[request_connect(ip, port, [callback])](https://ripple.com/wiki/RPC_API#connect)**
|
||||
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.setServer`. Example:
|
||||
|
||||
```js
|
||||
var request = remote.requestServerInfo();
|
||||
|
||||
request.setServer('wss://s1.ripple.com');
|
||||
|
||||
request.request(function(err, res) {
|
||||
|
||||
});
|
||||
```
|
||||
**[requestPeers([callback])](https://ripple.com/wiki/JSON_Messages#peers)**
|
||||
|
||||
**[requestConnect(ip, port, [callback])](https://ripple.com/wiki/JSON_Messages#connect)**
|
||||
|
||||
**[unl_list([callback])](https://ripple.com/wiki/JSON_Messages#unl_list)**
|
||||
|
||||
```js
|
||||
var request = remote.request('un_list');
|
||||
|
||||
request.setServer('wss://s1.ripple.com');
|
||||
|
||||
request.request(function(err, res) {
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
**[unl_add(addr, comment, [callback])](https://ripple.com/wiki/JSON_Messages#unl_add)**
|
||||
|
||||
**[unl_delete(node, [callback])](https://ripple.com/wiki/JSON_Messages#unl_delete)**
|
||||
|
||||
|
||||
|
||||
##Ledger query functions
|
||||
##Ledger requests
|
||||
|
||||
**[request_ledger(ledger, [opts], [callback])](https://ripple.com/wiki/RPC_API#ledger)**
|
||||
**[requestLedger([opts], [callback])](https://ripple.com/wiki/JSON_Messages#ledger)**
|
||||
|
||||
**request_ledger_header([callback])**
|
||||
**[requestLedgerHeader([callback])](https://wiki.ripple.com/JSON_Messages#ledger_data)**
|
||||
|
||||
**[request_ledger_current([callback])](https://ripple.com/wiki/RPC_API#ledger_current)**
|
||||
**[requestLedgerCurrent([callback])](https://ripple.com/wiki/JSON_Messages#ledger_current)**
|
||||
|
||||
**[request_ledger_entry(type, [callback])](https://ripple.com/wiki/RPC_API#ledger_entry)**
|
||||
**[requestLedgerEntry(type, [callback])](https://ripple.com/wiki/JSON_Messages#ledger_entry)**
|
||||
|
||||
**[request_subscribe(streams, [callback])](https://ripple.com/wiki/RPC_API#subscribe)**
|
||||
**[requestSubscribe([streams], [callback])](https://ripple.com/wiki/JSON_Messages#subscribe)**
|
||||
|
||||
Start receiving selected streams from the server.
|
||||
|
||||
**[request_unsubscribe(streams, [callback])](https://ripple.com/wiki/RPC_API#unsubscribe)**
|
||||
**[requestUnsubscribe([streams], [callback])](https://ripple.com/wiki/JSON_Messages#unsubscribe)**
|
||||
|
||||
Stop receiving selected streams from the server.
|
||||
|
||||
##Account requests
|
||||
|
||||
|
||||
|
||||
##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)**
|
||||
**[requestAccountInfo(options, [callback])](https://ripple.com/wiki/JSON_Messages#account_info)**
|
||||
|
||||
Return information about the specified account.
|
||||
|
||||
```
|
||||
var options = {
|
||||
account: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
|
||||
ledger: 'validated'
|
||||
};
|
||||
|
||||
var request = remote.requestAccountInfo(options, function(err, info) {
|
||||
/* process info */
|
||||
});
|
||||
|
||||
|
||||
// response
|
||||
{
|
||||
ledger_current_index: <number>,
|
||||
account_data: {
|
||||
@@ -143,21 +155,43 @@ Return information about the specified account.
|
||||
}
|
||||
```
|
||||
|
||||
**[request_account_lines(accountID, account_index, current, [callback])](https://ripple.com/wiki/RPC_API#account_lines)**
|
||||
**[requestAccountLines(options, [callback])](https://ripple.com/wiki/JSON_Messages#account_lines)**
|
||||
|
||||
**[request_account_offers(accountID, account_index, current, [callback])](https://ripple.com/wiki/RPC_API#account_offers)**
|
||||
**[requestAccountOffers(options, [callback])](https://ripple.com/wiki/JSON_Messages#account_offers)**
|
||||
|
||||
Return the specified account's outstanding offers.
|
||||
|
||||
**[request_account_tx(opts, [callback])](https://ripple.com/wiki/RPC_API#account_tx)**
|
||||
Requests for both `account_lines` and `account_offers` support paging. The amount of results per response can be configured with the `limit`.
|
||||
The responses can be paged through by using the `marker`.
|
||||
|
||||
```
|
||||
// A valid `ledger_index` or `ledger_hash` is required to provide a reliable result.
|
||||
// Results can change between ledger closes, so the provided ledger will be used as base.
|
||||
var options = {
|
||||
account: < rippleAccount >,
|
||||
limit: < Number between 10 and 400 >,
|
||||
ledger: < valid ledger_index or ledger_hash >
|
||||
}
|
||||
|
||||
// The `marker` comes back in an account request if there are more results than are returned
|
||||
// in the current response. The amount of results per response are determined by the `limit`.
|
||||
if (marker) {
|
||||
options.marker = < marker >;
|
||||
}
|
||||
|
||||
var request = remote.requestAccountOffers(options);
|
||||
```
|
||||
|
||||
|
||||
**[requestAccountTransactions(options, [callback])](https://ripple.com/wiki/JSON_Messages#account_tx)**
|
||||
|
||||
Fetch a list of transactions that applied to this account.
|
||||
|
||||
Options:
|
||||
|
||||
+ `account`
|
||||
+ `ledger_index_min` *deprecated, -1*
|
||||
+ `ledger_index_max` *deprecated, -1*
|
||||
+ `ledger_index_min`
|
||||
+ `ledger_index_max`
|
||||
+ `binary` *false*
|
||||
+ `count` *false*
|
||||
+ `descending` *false*
|
||||
@@ -167,92 +201,154 @@ Options:
|
||||
+ `fwd_marker`
|
||||
+ `rev_marker`
|
||||
|
||||
**[request_wallet_accounts(seed, [callback])](https://ripple.com/wiki/RPC_API#wallet_accounts)**
|
||||
**[requestWalletAccounts(seed, [callback])](https://ripple.com/wiki/JSON_Messages#wallet_accounts)**
|
||||
|
||||
Return a list of accounts for a wallet.
|
||||
Return a list of accounts for a wallet. *Requires trusted remote*
|
||||
|
||||
+ requires trusted remote
|
||||
|
||||
**request_account_balance(account, ledger, [callback])**
|
||||
**requestAccountBalance(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])**
|
||||
**requestAccountFlags(account, [ledger], [callback])**
|
||||
|
||||
Return the flags for an account.
|
||||
|
||||
**request_owner_count(account, current, [callback])**
|
||||
**requestOwnerCount(account, [ledger], [callback])**
|
||||
|
||||
Return the owner count for an account.
|
||||
|
||||
**request_ripple_balance(account, issuer, currency, current, [callback])**
|
||||
**requestRippleBalance(account, issuer, currency, [ledger], [callback])**
|
||||
|
||||
Return a request to get a ripple balance
|
||||
|
||||
##Orderbook requests
|
||||
|
||||
**[requestBookOffers(options, [callback])](https://ripple.com/wiki/JSON_Messages#book_offers)**
|
||||
|
||||
|
||||
##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.
|
||||
Return the offers for an order book, also called a *snapshot*
|
||||
|
||||
```js
|
||||
var request = remote.request_book_offers({
|
||||
var options = {
|
||||
gets: {
|
||||
'currency':'XRP'
|
||||
issuer: < issuer >,
|
||||
currency: < currency >
|
||||
},
|
||||
pays: {
|
||||
'currency':'USD',
|
||||
'issuer': 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
|
||||
}
|
||||
});
|
||||
issuer: < issuer >,
|
||||
currency: < currency >
|
||||
},
|
||||
limit: < limit >
|
||||
};
|
||||
|
||||
request.request();
|
||||
var request = remote.requestBookOffers(options);
|
||||
|
||||
request.request(function(err, offers) {
|
||||
//handle offers
|
||||
});
|
||||
```
|
||||
|
||||
##Transaction requests
|
||||
|
||||
**[requestTransactionEntry(hash, [ledger_hash], [callback])](https://ripple.com/wiki/JSON_Messages#transaction_entry)**
|
||||
|
||||
Searches a particular ledger for a transaction hash. Default ledger is the open ledger.
|
||||
|
||||
##Transaction submission functions
|
||||
**[requestTransaction(hash, [callback])](https://ripple.com/wiki/JSON_Messages#tx)**
|
||||
|
||||
**[request_sign(secret, tx_json, [callback])](https://ripple.com/wiki/RPC_API#sign)**
|
||||
Searches ledger history for validated transaction hashes.
|
||||
|
||||
Sign a transaction.
|
||||
**[requestSign(secret, tx_json, [callback])](https://ripple.com/wiki/JSON_Messages#sign)**
|
||||
|
||||
+ requires trusted remote
|
||||
Sign a transaction. *Requires trusted remote*
|
||||
|
||||
**[request_submit([callback])](https://ripple.com/wiki/RPC_API#submit)**
|
||||
**[requestSubmit([callback])](https://ripple.com/wiki/JSON_Messages#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.
|
||||
|
||||
**[pathFind(src_account, dst_account, dst_amount, src_currencies)](https://ripple.com/wiki/JSON_Messages#path_find)**
|
||||
|
||||
**[request_ripple_path_find(src_account, dst_account, dst_amount, src_currencies, [callback])](https://ripple.com/wiki/RPC_API#path_find)**
|
||||
#Transaction constructors
|
||||
|
||||
Use `remote.createTransaction('TransactionType', [options])` to construct a transaction. To submit, use `transaction.submit([callback])`.
|
||||
|
||||
**transaction([destination], [source], [amount], [callback])**
|
||||
**Payment**
|
||||
|
||||
Returns a [Transaction](https://github.com/ripple/ripple-lib/blob/develop/src/js/ripple/transaction.js) object
|
||||
```js
|
||||
var transaction = remote.createTransaction('Payment', {
|
||||
account: MY_ADDRESS,
|
||||
destination: DEST_ADDRESS,
|
||||
amount: AMOUNT
|
||||
});
|
||||
```
|
||||
|
||||
**AccountSet**
|
||||
|
||||
#3. Transaction events
|
||||
```js
|
||||
var transaction = remote.createTransaction('AccountSet', {
|
||||
account: MY_ADDRESS,
|
||||
set: 'RequireDest',
|
||||
clear: 'RequireAuth'
|
||||
});
|
||||
```
|
||||
|
||||
**TrustSet**
|
||||
|
||||
```js
|
||||
var transaction = remote.createTransaction('TrustSet', {
|
||||
account: MY_ADDRESS,
|
||||
limit: '1/USD/rrrrrrrrrrrrrrrrrrrrBZbvji'
|
||||
});
|
||||
```
|
||||
|
||||
**OfferCreate**
|
||||
|
||||
```js
|
||||
var transaction = remote.createTransaction('OfferCreate', {
|
||||
account: MY_ADDRESS,
|
||||
taker_pays: '1',
|
||||
taker_gets: '1/USD/rrrrrrrrrrrrrrrrrrrrBZbvji'
|
||||
});
|
||||
```
|
||||
|
||||
##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.
|
||||
+ `presubmit` Immediately before transaction is submitted
|
||||
+ `postsubmit` Immediately after transaction is submitted
|
||||
+ `submitted` Transaction has been submitted to the network. The submission may result in a remote error or success.
|
||||
+ `resubmitted` Transaction is beginning resubmission.
|
||||
+ `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.
|
||||
|
||||
##Complete payment example
|
||||
|
||||
#4. Amount objects
|
||||
```js
|
||||
remote.setSecret(MY_ADDRESS, MY_SECRET);
|
||||
|
||||
var transaction = remote.createTransaction('Payment', {
|
||||
account: MY_ADDRESS,
|
||||
destination: DEST_ADDRESS,
|
||||
amount: AMOUNT
|
||||
});
|
||||
|
||||
transaction.on('resubmitted', function() {
|
||||
// initial submission failed, resubmitting
|
||||
});
|
||||
|
||||
transaction.submit(function(err, res) {
|
||||
// submission has finalized with either an error or success.
|
||||
// the transaction will not be retried after this point
|
||||
});
|
||||
```
|
||||
|
||||
#Amount objects
|
||||
|
||||
Coming Soon
|
||||
|
||||
168
docs/VAULTCLIENT.md
Normal file
168
docs/VAULTCLIENT.md
Normal 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
|
||||
185
npm-shrinkwrap.json
generated
Normal file
185
npm-shrinkwrap.json
generated
Normal file
@@ -0,0 +1,185 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.12.1-rc3",
|
||||
"dependencies": {
|
||||
"async": {
|
||||
"version": "0.9.0",
|
||||
"from": "async@>=0.9.0 <0.10.0",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-0.9.0.tgz"
|
||||
},
|
||||
"bignumber.js": {
|
||||
"version": "2.0.3",
|
||||
"from": "bignumber.js@>=2.0.3 <3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-2.0.3.tgz"
|
||||
},
|
||||
"extend": {
|
||||
"version": "1.2.1",
|
||||
"from": "extend@>=1.2.1 <1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/extend/-/extend-1.2.1.tgz"
|
||||
},
|
||||
"lodash": {
|
||||
"version": "3.3.1",
|
||||
"from": "https://registry.npmjs.org/lodash/-/lodash-3.3.1.tgz",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-3.3.1.tgz"
|
||||
},
|
||||
"lru-cache": {
|
||||
"version": "2.5.0",
|
||||
"from": "lru-cache@>=2.5.0 <2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.5.0.tgz"
|
||||
},
|
||||
"ripple-wallet-generator": {
|
||||
"version": "1.0.2",
|
||||
"from": "ripple-wallet-generator@1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/ripple-wallet-generator/-/ripple-wallet-generator-1.0.2.tgz"
|
||||
},
|
||||
"superagent": {
|
||||
"version": "0.18.2",
|
||||
"from": "superagent@>=0.18.0 <0.19.0",
|
||||
"resolved": "https://registry.npmjs.org/superagent/-/superagent-0.18.2.tgz",
|
||||
"dependencies": {
|
||||
"qs": {
|
||||
"version": "0.6.6",
|
||||
"from": "qs@0.6.6",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz"
|
||||
},
|
||||
"formidable": {
|
||||
"version": "1.0.14",
|
||||
"from": "formidable@1.0.14",
|
||||
"resolved": "https://registry.npmjs.org/formidable/-/formidable-1.0.14.tgz"
|
||||
},
|
||||
"mime": {
|
||||
"version": "1.2.11",
|
||||
"from": "mime@1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz"
|
||||
},
|
||||
"component-emitter": {
|
||||
"version": "1.1.2",
|
||||
"from": "component-emitter@1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz"
|
||||
},
|
||||
"methods": {
|
||||
"version": "1.0.1",
|
||||
"from": "methods@1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz"
|
||||
},
|
||||
"cookiejar": {
|
||||
"version": "2.0.1",
|
||||
"from": "cookiejar@2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.0.1.tgz"
|
||||
},
|
||||
"debug": {
|
||||
"version": "1.0.4",
|
||||
"from": "debug@>=1.0.1 <1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-1.0.4.tgz",
|
||||
"dependencies": {
|
||||
"ms": {
|
||||
"version": "0.6.2",
|
||||
"from": "ms@0.6.2",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"reduce-component": {
|
||||
"version": "1.0.1",
|
||||
"from": "reduce-component@1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/reduce-component/-/reduce-component-1.0.1.tgz"
|
||||
},
|
||||
"form-data": {
|
||||
"version": "0.1.3",
|
||||
"from": "form-data@0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-0.1.3.tgz",
|
||||
"dependencies": {
|
||||
"combined-stream": {
|
||||
"version": "0.0.7",
|
||||
"from": "combined-stream@>=0.0.4 <0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-0.0.7.tgz",
|
||||
"dependencies": {
|
||||
"delayed-stream": {
|
||||
"version": "0.0.5",
|
||||
"from": "delayed-stream@0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-0.0.5.tgz"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"readable-stream": {
|
||||
"version": "1.0.27-1",
|
||||
"from": "readable-stream@1.0.27-1",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.27-1.tgz",
|
||||
"dependencies": {
|
||||
"core-util-is": {
|
||||
"version": "1.0.1",
|
||||
"from": "core-util-is@>=1.0.0 <1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz"
|
||||
},
|
||||
"isarray": {
|
||||
"version": "0.0.1",
|
||||
"from": "isarray@0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz"
|
||||
},
|
||||
"string_decoder": {
|
||||
"version": "0.10.31",
|
||||
"from": "string_decoder@>=0.10.0 <0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz"
|
||||
},
|
||||
"inherits": {
|
||||
"version": "2.0.1",
|
||||
"from": "inherits@>=2.0.1 <2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ws": {
|
||||
"version": "0.7.1",
|
||||
"from": "ws@>=0.7.1 <0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-0.7.1.tgz",
|
||||
"dependencies": {
|
||||
"options": {
|
||||
"version": "0.0.6",
|
||||
"from": "options@>=0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz"
|
||||
},
|
||||
"ultron": {
|
||||
"version": "1.0.1",
|
||||
"from": "ultron@>=1.0.0 <1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.1.tgz"
|
||||
},
|
||||
"bufferutil": {
|
||||
"version": "1.0.1",
|
||||
"from": "bufferutil@>=1.0.0 <1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-1.0.1.tgz",
|
||||
"dependencies": {
|
||||
"bindings": {
|
||||
"version": "1.2.1",
|
||||
"from": "bindings@>=1.2.0 <1.3.0"
|
||||
},
|
||||
"nan": {
|
||||
"version": "1.6.1",
|
||||
"from": "nan@>=1.6.0 <1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-1.6.1.tgz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"version": "1.0.1",
|
||||
"from": "utf-8-validate@>=1.0.0 <1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-1.0.1.tgz",
|
||||
"dependencies": {
|
||||
"bindings": {
|
||||
"version": "1.2.1",
|
||||
"from": "bindings@>=1.2.0 <1.3.0"
|
||||
},
|
||||
"nan": {
|
||||
"version": "1.6.1",
|
||||
"from": "nan@>=1.6.0 <1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-1.6.1.tgz"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
56
package.json
56
package.json
@@ -1,41 +1,59 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.7.35",
|
||||
"description": "Ripple JavaScript client library",
|
||||
"version": "0.12.1-rc3",
|
||||
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
|
||||
"files": [
|
||||
"src/js/*",
|
||||
"bin/*",
|
||||
"build/*",
|
||||
"test/*",
|
||||
"Makefile",
|
||||
"Gruntfile.js"
|
||||
"Gulpfile.js"
|
||||
],
|
||||
"main": "src/js/ripple",
|
||||
"directories": {
|
||||
"test": "test"
|
||||
},
|
||||
"dependencies": {
|
||||
"async": "~0.2.10",
|
||||
"ws": "~0.4.31",
|
||||
"async": "~0.9.0",
|
||||
"bignumber.js": "^2.0.3",
|
||||
"extend": "~1.2.1",
|
||||
"jshint-loader": "~0.5.0",
|
||||
"lru-cache": "~2.5.0"
|
||||
"lodash": "^3.1.0",
|
||||
"lru-cache": "~2.5.0",
|
||||
"ripple-wallet-generator": "1.0.2",
|
||||
"ws": "~0.7.1",
|
||||
"superagent": "^0.18.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",
|
||||
"mocha": "~1.14.0",
|
||||
"sinon-chai": "~2.4.0",
|
||||
"sinon": "~1.7.3"
|
||||
"assert-diff": "^1.0.1",
|
||||
"coveralls": "~2.10.0",
|
||||
"eslint": "^0.13.0",
|
||||
"gulp": "~3.8.10",
|
||||
"gulp-bump": "~0.1.13",
|
||||
"gulp-clean-dest": "^0.1.0",
|
||||
"gulp-concat": "~2.4.3",
|
||||
"gulp-filelog": "^0.4.1",
|
||||
"gulp-flowtype": "^0.4.1",
|
||||
"gulp-plumber": "^0.6.6",
|
||||
"gulp-react": "^2.0.0",
|
||||
"gulp-rename": "~1.2.0",
|
||||
"gulp-uglify": "~1.1.0",
|
||||
"gulp-util": "^3.0.3",
|
||||
"gulp-watch": "^4.1.0",
|
||||
"istanbul": "~0.3.5",
|
||||
"map-stream": "~0.1.0",
|
||||
"mocha": "~2.1.0",
|
||||
"nock": "^0.34.1",
|
||||
"webpack": "~1.5.3",
|
||||
"yargs": "~1.3.1"
|
||||
},
|
||||
"scripts": {
|
||||
"pretest": "node_modules/.bin/grunt",
|
||||
"test": "mocha test/*-test.js",
|
||||
"build": "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/mocha/bin/_mocha -- --reporter ${MOCHA_REPORTER:=spec} test/*-test.js",
|
||||
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls",
|
||||
"lint": "if ! [ -f eslintrc ]; then curl -o eslintrc 'https://raw.githubusercontent.com/ripple/javascript-style-guide/master/eslintrc'; fi; eslint --reset -c eslintrc src/js/ripple/*.js",
|
||||
"perf": "./scripts/perf_test.sh"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
11
scripts/perf_test.sh
Executable file
11
scripts/perf_test.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
URL="https://www.dropbox.com/s/a0gy7vbb86eeqlq/ledger-full-1000000.json?dl=1"
|
||||
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
|
||||
DEST="$DIR/cache/ledger-full-1000000.json"
|
||||
if [ ! -e "$DEST" ]
|
||||
then
|
||||
echo "Downloading test data..."
|
||||
mkdir -p "$DIR/cache"
|
||||
curl -L "$URL" > "$DEST"
|
||||
fi
|
||||
time node "$DIR/verify_ledger_json.js" "$DEST"
|
||||
43
scripts/publish
Normal file
43
scripts/publish
Normal file
@@ -0,0 +1,43 @@
|
||||
echo "PUBLISH"
|
||||
|
||||
function exit_on_error {
|
||||
res=$?
|
||||
[[ ${res:-99} -eq 0 ]] || exit $res
|
||||
}
|
||||
|
||||
rm -rf build
|
||||
|
||||
npm install
|
||||
gulp
|
||||
npm test
|
||||
exit_on_error
|
||||
|
||||
echo ""
|
||||
echo "publish to npm"
|
||||
npm publish
|
||||
exit_on_error
|
||||
|
||||
rm -rf dist
|
||||
echo ""
|
||||
echo "publish to bower"
|
||||
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
gulp bower
|
||||
exit_on_error
|
||||
|
||||
cd dist
|
||||
version=$(cat bower.json | grep -Eo '([0-9]\.?)+(-rc[0-9])?')
|
||||
echo "version: $version"
|
||||
git add ripple.js ripple-debug.js ripple-min.js bower.json
|
||||
exit_on_error
|
||||
|
||||
git commit -m "[TASK] add v$version"
|
||||
exit_on_error
|
||||
|
||||
git tag "v$version"
|
||||
exit_on_error
|
||||
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
|
||||
cd ..
|
||||
43
scripts/publish_rc
Normal file
43
scripts/publish_rc
Normal file
@@ -0,0 +1,43 @@
|
||||
echo "PUBLISH RELEASE CANDIDATE"
|
||||
|
||||
function exit_on_error {
|
||||
res=$?
|
||||
[[ ${res:-99} -eq 0 ]] || exit $res
|
||||
}
|
||||
|
||||
rm -rf build
|
||||
|
||||
npm install
|
||||
gulp
|
||||
npm test
|
||||
exit_on_error
|
||||
|
||||
echo ""
|
||||
echo "publish rc to npm"
|
||||
npm publish --tag beta
|
||||
exit_on_error
|
||||
|
||||
rm -rf dist
|
||||
echo ""
|
||||
echo "publish to bower"
|
||||
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
gulp bower
|
||||
exit_on_error
|
||||
|
||||
cd dist
|
||||
version=$(cat bower.json | grep -Eo '([0-9]\.?)+(-rc[0-9])?')
|
||||
echo "version: $version"
|
||||
git add ripple.js ripple-debug.js ripple-min.js bower.json
|
||||
exit_on_error
|
||||
|
||||
git commit -m "[TASK] add v$version"
|
||||
exit_on_error
|
||||
|
||||
git tag "v$version"
|
||||
exit_on_error
|
||||
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
|
||||
cd ..
|
||||
12
scripts/publish_to_bower
Normal file
12
scripts/publish_to_bower
Normal file
@@ -0,0 +1,12 @@
|
||||
rm -rf dist
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
gulp bower
|
||||
cd dist
|
||||
version=$(cat bower.json | grep -Eo '([0-9]\.?)+(-rc[0-9])?')
|
||||
echo "version: $version"
|
||||
git add ripple.js ripple-debug.js ripple-min.js bower.json
|
||||
git commit -m "[TASK] add v$version"
|
||||
git tag "v$version"
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
cd ..
|
||||
43
scripts/verify_ledger_json.js
Normal file → Executable file
43
scripts/verify_ledger_json.js
Normal file → Executable file
@@ -1,14 +1,49 @@
|
||||
var fs = require('fs');
|
||||
var Ledger = require('../src/js/ripple/ledger').Ledger;
|
||||
|
||||
if (process.argc < 1) {
|
||||
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(process.argv[2], 'utf-8');
|
||||
var json = fs.readFileSync(opts.argv[0], 'utf-8');
|
||||
var ledger = Ledger.from_json(JSON.parse(json));
|
||||
|
||||
console.log("Calculated transaction hash: "+ledger.calc_tx_hash().to_hex())
|
||||
console.log("Transaction hash in header: "+ledger.ledger_json.transaction_hash);
|
||||
// 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());
|
||||
|
||||
1210
src/js/jsbn/jsbn.js
1210
src/js/jsbn/jsbn.js
File diff suppressed because it is too large
Load Diff
@@ -9,14 +9,16 @@
|
||||
// balance_proposed
|
||||
//
|
||||
|
||||
// var network = require("./network.js");
|
||||
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
// 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;
|
||||
|
||||
/**
|
||||
* @constructor Account
|
||||
@@ -29,10 +31,10 @@ function Account(remote, account) {
|
||||
|
||||
var self = this;
|
||||
|
||||
this._remote = remote;
|
||||
this._account = UInt160.from_json(account);
|
||||
this._remote = remote;
|
||||
this._account = UInt160.from_json(account);
|
||||
this._account_id = this._account.to_json();
|
||||
this._subs = 0;
|
||||
this._subs = 0;
|
||||
|
||||
// Ledger entry object
|
||||
// Important: This must never be overwritten, only extend()-ed
|
||||
@@ -43,7 +45,7 @@ function Account(remote, account) {
|
||||
if (!self._subs && self._remote._connected) {
|
||||
self._remote.request_subscribe()
|
||||
.add_account(self._account_id)
|
||||
.broadcast();
|
||||
.broadcast().request();
|
||||
}
|
||||
self._subs += 1;
|
||||
}
|
||||
@@ -57,7 +59,7 @@ function Account(remote, account) {
|
||||
if (!self._subs && self._remote._connected) {
|
||||
self._remote.request_unsubscribe()
|
||||
.add_account(self._account_id)
|
||||
.broadcast();
|
||||
.broadcast().request();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -73,7 +75,9 @@ function Account(remote, account) {
|
||||
this._remote.on('prepare_subscribe', attachAccount);
|
||||
|
||||
function handleTransaction(transaction) {
|
||||
if (!transaction.mmeta) return;
|
||||
if (!transaction.mmeta) {
|
||||
return;
|
||||
}
|
||||
|
||||
var changed = false;
|
||||
|
||||
@@ -128,14 +132,14 @@ Account.prototype.isValid = function() {
|
||||
*/
|
||||
|
||||
Account.prototype.getInfo = function(callback) {
|
||||
return this._remote.request_account_info(this._account_id, callback);
|
||||
return this._remote.requestAccountInfo({account: 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} callback
|
||||
*/
|
||||
@@ -162,13 +166,16 @@ Account.prototype.entry = function(callback) {
|
||||
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 (err &&
|
||||
"object" === typeof err &&
|
||||
"object" === typeof err.remote &&
|
||||
err.remote.error === "actNotFound") {
|
||||
// New accounts will start out as sequence zero
|
||||
callback(null, 0);
|
||||
if (isNotFound(err)) {
|
||||
// New accounts will start out as sequence one
|
||||
callback(null, 1);
|
||||
} else if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
@@ -185,7 +192,7 @@ Account.prototype.getNextSequence = function(callback) {
|
||||
* 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.)
|
||||
* 'lines' event. (Not yet implemented.)
|
||||
*
|
||||
* @param {function(err, lines)} callback Called with the result
|
||||
*/
|
||||
@@ -204,7 +211,7 @@ Account.prototype.lines = function(callback) {
|
||||
}
|
||||
}
|
||||
|
||||
this._remote.requestAccountLines(this._account_id, accountLines);
|
||||
this._remote.requestAccountLines({account: this._account_id}, accountLines);
|
||||
|
||||
return this;
|
||||
};
|
||||
@@ -218,23 +225,27 @@ Account.prototype.lines = function(callback) {
|
||||
* @returns {Account}
|
||||
*/
|
||||
|
||||
Account.prototype.line = function(currency,address,callback) {
|
||||
Account.prototype.line = function(currency, address, callback) {
|
||||
var self = this;
|
||||
var found;
|
||||
var callback = typeof callback === 'function' ? callback : function(){};
|
||||
|
||||
self.lines(function(err, data) {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
var line = data.lines.filter(function(line) {
|
||||
if (line.account === address && line.currency === currency) {
|
||||
return line;
|
||||
}
|
||||
})[0];
|
||||
|
||||
callback(null, line);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
callback(null, line);
|
||||
});
|
||||
|
||||
return this;
|
||||
@@ -254,17 +265,21 @@ 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', transaction);
|
||||
|
||||
var account = transaction.transaction.Account;
|
||||
|
||||
if (!account) return;
|
||||
|
||||
var isThisAccount = account === this._account_id;
|
||||
|
||||
this.emit(isThisAccount ? 'transaction-outbound' : 'transaction-inbound', transaction);
|
||||
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);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -278,6 +293,104 @@ 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;
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,136 +1,126 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
'use strict';
|
||||
var _ = require('lodash');
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var extend = require('extend');
|
||||
var convertBase = require('./baseconverter');
|
||||
|
||||
var Base = {};
|
||||
|
||||
var alphabets = Base.alphabets = {
|
||||
ripple : "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
|
||||
tipple : "RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz",
|
||||
bitcoin : "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
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
|
||||
});
|
||||
|
||||
function sha256(bytes) {
|
||||
return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
|
||||
};
|
||||
return sjcl.codec.bytes.fromBits(
|
||||
sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
|
||||
}
|
||||
|
||||
function sha256hash(bytes) {
|
||||
return sha256(sha256(bytes));
|
||||
};
|
||||
function encodeString(alphabet, input) {
|
||||
if (input.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var leadingZeros = _.takeWhile(input, function(d) {
|
||||
return d === 0;
|
||||
});
|
||||
var out = convertBase(input, 256, 58).map(function(digit) {
|
||||
if (digit < 0 || digit >= alphabet.length) {
|
||||
throw new Error('Value ' + digit + ' is out of bounds for encoding');
|
||||
}
|
||||
return alphabet[digit];
|
||||
});
|
||||
var prefix = leadingZeros.map(function() {
|
||||
return alphabet[0];
|
||||
});
|
||||
return prefix.concat(out).join('');
|
||||
}
|
||||
|
||||
function decodeString(indexes, input) {
|
||||
if (input.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var input58 = input.split('').map(function(c) {
|
||||
var charCode = c.charCodeAt(0);
|
||||
if (charCode >= indexes.length) {
|
||||
throw new Error('Character ' + c + ' is not valid for encoding');
|
||||
}
|
||||
return indexes[charCode];
|
||||
});
|
||||
var leadingZeros = _.takeWhile(input58, function(d) {
|
||||
return d === 0;
|
||||
});
|
||||
var out = convertBase(input58, 58, 256);
|
||||
return leadingZeros.concat(out);
|
||||
}
|
||||
|
||||
function Base58(alphabet) {
|
||||
var indexes = utils.arraySet(128, -1);
|
||||
for (var i = 0; i < alphabet.length; i++) {
|
||||
indexes[alphabet.charCodeAt(i)] = i;
|
||||
}
|
||||
return {
|
||||
decode: decodeString.bind(null, indexes),
|
||||
encode: encodeString.bind(null, alphabet)
|
||||
};
|
||||
}
|
||||
|
||||
Base.encoders = {};
|
||||
Object.keys(alphabets).forEach(function(alphabet) {
|
||||
Base.encoders[alphabet] = new Base58(alphabets[alphabet]);
|
||||
});
|
||||
|
||||
// --> 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 = new BigInteger();
|
||||
var bi_r = new BigInteger();
|
||||
var bi_value = new BigInteger(input);
|
||||
var buffer = [];
|
||||
|
||||
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()]);
|
||||
}
|
||||
|
||||
for (var i=0; i !== input.length && !input[i]; i += 1) {
|
||||
buffer.push(alphabet[0]);
|
||||
}
|
||||
|
||||
return buffer.reverse().join('');
|
||||
Base.encode = function(input, alpha) {
|
||||
return this.encoders[alpha || 'ripple'].encode(input);
|
||||
};
|
||||
|
||||
// --> input: String
|
||||
// <-- array of bytes or undefined.
|
||||
Base.decode = function (input, alpha) {
|
||||
Base.decode = function(input, alpha) {
|
||||
if (typeof input !== 'string') {
|
||||
return void(0);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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 !== input.length; i += 1) {
|
||||
var v = alphabet.indexOf(input[i]);
|
||||
|
||||
if (v < 0) {
|
||||
return void(0);
|
||||
}
|
||||
|
||||
var r = new BigInteger();
|
||||
r.fromInt(v);
|
||||
bi_value = bi_value.multiply(bi_base).add(r);
|
||||
try {
|
||||
return this.encoders[alpha || 'ripple'].decode(input);
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// toByteArray:
|
||||
// - Returns leading zeros!
|
||||
// - Returns signed bytes!
|
||||
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]) {
|
||||
extra += 1;
|
||||
}
|
||||
|
||||
if (extra) {
|
||||
bytes = bytes.slice(extra);
|
||||
}
|
||||
|
||||
var zeros = 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);
|
||||
Base.verify_checksum = function(bytes) {
|
||||
var computed = sha256(sha256(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]) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return _.isEqual(computed, checksum);
|
||||
};
|
||||
|
||||
// --> input: Array
|
||||
// <-- String
|
||||
Base.encode_check = function (version, input, alphabet) {
|
||||
Base.encode_check = function(version, input, alphabet) {
|
||||
var buffer = [].concat(version, input);
|
||||
var check = sha256(sha256(buffer)).slice(0, 4);
|
||||
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) {
|
||||
// <-- NaN || sjcl.bn
|
||||
Base.decode_check = function(version, input, alphabet) {
|
||||
var buffer = Base.decode(input, alphabet);
|
||||
|
||||
if (!buffer || buffer.length < 5) {
|
||||
@@ -143,16 +133,10 @@ Base.decode_check = function (version, input, alphabet) {
|
||||
}
|
||||
|
||||
// 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 (Array.isArray(version) && _.every(version, function(v) {
|
||||
return v !== buffer[0];
|
||||
})) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
if (!Base.verify_checksum(buffer)) {
|
||||
@@ -163,7 +147,8 @@ Base.decode_check = function (version, input, alphabet) {
|
||||
// intrepret the value as a negative number
|
||||
buffer[0] = 0;
|
||||
|
||||
return new BigInteger(buffer.slice(0, -4), 256);
|
||||
return sjcl.bn.fromBits(
|
||||
sjcl.codec.bytes.toBits(buffer.slice(0, -4)));
|
||||
};
|
||||
|
||||
exports.Base = Base;
|
||||
|
||||
32
src/js/ripple/baseconverter.js
Normal file
32
src/js/ripple/baseconverter.js
Normal file
@@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
function normalize(digitArray) {
|
||||
while (digitArray[0] === 0) {
|
||||
digitArray.shift();
|
||||
}
|
||||
return digitArray;
|
||||
}
|
||||
|
||||
function divmod(digitArray, base, divisor) {
|
||||
var remainder = 0;
|
||||
var quotient = [];
|
||||
for (var j = 0; j < digitArray.length; j++) {
|
||||
var temp = remainder * base + parseInt(digitArray[j], 10);
|
||||
quotient.push(Math.floor(temp / divisor));
|
||||
remainder = temp % divisor;
|
||||
}
|
||||
return {quotient: normalize(quotient), remainder: remainder};
|
||||
}
|
||||
|
||||
function convertBase(digitArray, fromBase, toBase) {
|
||||
var result = [];
|
||||
var dividend = digitArray;
|
||||
while (dividend.length > 0) {
|
||||
var qr = divmod(dividend, fromBase, toBase);
|
||||
result.unshift(qr.remainder);
|
||||
dividend = qr.quotient;
|
||||
}
|
||||
return normalize(result);
|
||||
}
|
||||
|
||||
module.exports = convertBase;
|
||||
@@ -1,10 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/*eslint no-multi-spaces:0,space-in-brackets:0,key-spacing:0,comma-spacing:0*/
|
||||
|
||||
/**
|
||||
* Data type map.
|
||||
*
|
||||
* Mapping of type ids to data types. The type id is specified by the high
|
||||
*
|
||||
* For reference, see rippled's definition:
|
||||
* https://github.com/ripple/rippled/blob/develop/src/ripple/data/protocol
|
||||
* /SField.cpp
|
||||
*/
|
||||
var TYPES_MAP = exports.types = [
|
||||
void(0),
|
||||
|
||||
exports.types = [
|
||||
undefined,
|
||||
|
||||
// Common
|
||||
'Int16', // 1
|
||||
@@ -17,11 +26,11 @@ var TYPES_MAP = exports.types = [
|
||||
'Account', // 8
|
||||
|
||||
// 9-13 reserved
|
||||
void(0), // 9
|
||||
void(0), // 10
|
||||
void(0), // 11
|
||||
void(0), // 12
|
||||
void(0), // 13
|
||||
undefined, // 9
|
||||
undefined, // 10
|
||||
undefined, // 11
|
||||
undefined, // 12
|
||||
undefined, // 13
|
||||
|
||||
'Object', // 14
|
||||
'Array', // 15
|
||||
@@ -106,7 +115,8 @@ var FIELDS_MAP = exports.fields = {
|
||||
16: 'BookDirectory',
|
||||
17: 'InvoiceID',
|
||||
18: 'Nickname',
|
||||
19: 'Feature'
|
||||
19: 'Amendment',
|
||||
20: 'TicketID'
|
||||
},
|
||||
6: { // Amount
|
||||
1: 'Amount',
|
||||
@@ -135,7 +145,8 @@ var FIELDS_MAP = exports.fields = {
|
||||
10: 'ExpireCode',
|
||||
11: 'CreateCode',
|
||||
12: 'MemoType',
|
||||
13: 'MemoData'
|
||||
13: 'MemoData',
|
||||
14: 'MemoFormat'
|
||||
},
|
||||
8: { // Account
|
||||
1: 'Account',
|
||||
@@ -146,7 +157,7 @@ var FIELDS_MAP = exports.fields = {
|
||||
8: 'RegularKey'
|
||||
},
|
||||
14: { // Object
|
||||
1: void(0), //end of Object
|
||||
1: undefined, // end of Object
|
||||
2: 'TransactionMetaData',
|
||||
3: 'CreatedNode',
|
||||
4: 'DeletedNode',
|
||||
@@ -158,7 +169,7 @@ var FIELDS_MAP = exports.fields = {
|
||||
10: 'Memo'
|
||||
},
|
||||
15: { // Array
|
||||
1: void(0), //end of Array
|
||||
1: undefined, // end of Array
|
||||
2: 'SigningAccounts',
|
||||
3: 'TxnSignatures',
|
||||
4: 'Signatures',
|
||||
@@ -187,7 +198,7 @@ var FIELDS_MAP = exports.fields = {
|
||||
19: { // Vector256
|
||||
1: 'Indexes',
|
||||
2: 'Hashes',
|
||||
3: 'Features'
|
||||
3: 'Amendments'
|
||||
}
|
||||
};
|
||||
|
||||
@@ -199,7 +210,6 @@ Object.keys(FIELDS_MAP).forEach(function(k1) {
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
var REQUIRED = exports.REQUIRED = 0,
|
||||
OPTIONAL = exports.OPTIONAL = 1,
|
||||
DEFAULT = exports.DEFAULT = 2;
|
||||
@@ -208,6 +218,7 @@ var base = [
|
||||
[ 'TransactionType' , REQUIRED ],
|
||||
[ 'Flags' , OPTIONAL ],
|
||||
[ 'SourceTag' , OPTIONAL ],
|
||||
[ 'LastLedgerSequence' , OPTIONAL ],
|
||||
[ 'Account' , REQUIRED ],
|
||||
[ 'Sequence' , REQUIRED ],
|
||||
[ 'Fee' , REQUIRED ],
|
||||
@@ -223,7 +234,9 @@ exports.tx = {
|
||||
[ 'WalletSize' , OPTIONAL ],
|
||||
[ 'MessageKey' , OPTIONAL ],
|
||||
[ 'Domain' , OPTIONAL ],
|
||||
[ 'TransferRate' , OPTIONAL ]
|
||||
[ 'TransferRate' , OPTIONAL ],
|
||||
[ 'SetFlag' , OPTIONAL ],
|
||||
[ 'ClearFlag' , OPTIONAL ]
|
||||
]),
|
||||
TrustSet: [20].concat(base, [
|
||||
[ 'LimitAmount' , OPTIONAL ],
|
||||
@@ -233,13 +246,14 @@ exports.tx = {
|
||||
OfferCreate: [7].concat(base, [
|
||||
[ 'TakerPays' , REQUIRED ],
|
||||
[ 'TakerGets' , REQUIRED ],
|
||||
[ 'Expiration' , OPTIONAL ]
|
||||
[ 'Expiration' , OPTIONAL ],
|
||||
[ 'OfferSequence' , OPTIONAL ]
|
||||
]),
|
||||
OfferCancel: [8].concat(base, [
|
||||
[ 'OfferSequence' , REQUIRED ]
|
||||
]),
|
||||
SetRegularKey: [5].concat(base, [
|
||||
[ 'RegularKey' , REQUIRED ]
|
||||
[ 'RegularKey' , OPTIONAL ]
|
||||
]),
|
||||
Payment: [0].concat(base, [
|
||||
[ 'Destination' , REQUIRED ],
|
||||
@@ -265,142 +279,123 @@ exports.tx = {
|
||||
EnableFeature: [100].concat(base, [
|
||||
[ 'Feature' , REQUIRED ]
|
||||
]),
|
||||
EnableAmendment: [100].concat(base, [
|
||||
[ 'Amendment' , REQUIRED ]
|
||||
]),
|
||||
SetFee: [101].concat(base, [
|
||||
[ 'Features' , REQUIRED ],
|
||||
[ 'BaseFee' , REQUIRED ],
|
||||
[ 'ReferenceFeeUnits' , REQUIRED ],
|
||||
[ 'ReserveBase' , REQUIRED ],
|
||||
[ 'ReserveIncrement' , REQUIRED ]
|
||||
]),
|
||||
TicketCreate: [10].concat(base, [
|
||||
[ 'Target' , OPTIONAL ],
|
||||
[ 'Expiration' , OPTIONAL ]
|
||||
]),
|
||||
TicketCancel: [11].concat(base, [
|
||||
[ 'TicketID' , REQUIRED ]
|
||||
])
|
||||
};
|
||||
|
||||
exports.ledger = {
|
||||
AccountRoot: [97],
|
||||
Contract: [99],
|
||||
DirectoryNode: [100],
|
||||
Features: [102],
|
||||
GeneratorMap: [103],
|
||||
LedgerHashes: [104],
|
||||
Nickname: [110],
|
||||
Offer: [111],
|
||||
RippleState: [114],
|
||||
FeeSettings: [115]
|
||||
};
|
||||
/*
|
||||
TODO:
|
||||
Need `base` factored out
|
||||
AccountRoot needs AccountTxnID
|
||||
var sleBase = [
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED]
|
||||
];
|
||||
|
||||
{
|
||||
'AccountRoot': [97,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['Sequence', REQUIRED],
|
||||
['PreviousTxnLgrSeq', REQUIRED],
|
||||
['TransferRate', OPTIONAL],
|
||||
['WalletSize', OPTIONAL],
|
||||
['OwnerCount', REQUIRED],
|
||||
['EmailHash', OPTIONAL],
|
||||
['PreviousTxnID', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['WalletLocator', OPTIONAL],
|
||||
['Balance', REQUIRED],
|
||||
['MessageKey', OPTIONAL,],
|
||||
['Domain', OPTIONAL,],
|
||||
['Account', REQUIRED],
|
||||
['RegularKey', OPTIONAL]],
|
||||
'Contract': [99,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['PreviousTxnLgrSeq', REQUIRED],
|
||||
['Expiration', REQUIRED],
|
||||
['BondAmount', REQUIRED],
|
||||
['PreviousTxnID', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['Balance', REQUIRED],
|
||||
['FundCode', OPTIONAL],
|
||||
['RemoveCode', OPTIONAL],
|
||||
['ExpireCode', OPTIONAL],
|
||||
['CreateCode', OPTIONAL],
|
||||
['Account', REQUIRED],
|
||||
['Owner', REQUIRED],
|
||||
['Issuer', REQUIRED]],
|
||||
'DirectoryNode': [100,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['IndexNext', OPTIONAL],
|
||||
['IndexPrevious', OPTIONAL],
|
||||
['ExchangeRate', OPTIONAL],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['RootIndex', REQUIRED],
|
||||
['Owner', OPTIONAL],
|
||||
['TakerPaysCurrency', OPTIONAL],
|
||||
['TakerPaysIssuer', OPTIONAL],
|
||||
['TakerGetsCurrency', OPTIONAL],
|
||||
['TakerGetsIssuer', OPTIONAL],
|
||||
['Indexes', REQUIRED]],
|
||||
'EnabledFeatures': [102,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['Features', REQUIRED]],
|
||||
'FeeSettings': [115,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['ReferenceFeeUnits', REQUIRED],
|
||||
['ReserveBase', REQUIRED],
|
||||
['ReserveIncrement', REQUIRED],
|
||||
['BaseFee', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL]],
|
||||
'GeneratorMap': [103,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['Generator', REQUIRED,]],
|
||||
'LedgerHashes': [104,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['FirstLedgerSequence', OPTIONAL],
|
||||
['LastLedgerSequence', OPTIONAL],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['Hashes', REQUIRED]],
|
||||
'Nickname': [110,
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED],
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['MinimumOffer', OPTIONAL],
|
||||
['Account', REQUIRED]],
|
||||
'Offer': [111,
|
||||
['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,
|
||||
['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.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 ],
|
||||
@@ -409,23 +404,35 @@ exports.metadata = [
|
||||
];
|
||||
|
||||
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
|
||||
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, // Deprecated, old ambiguous unfunded.
|
||||
tecMASTER_DISABLED : 130,
|
||||
tecNO_REGULAR_KEY : 131,
|
||||
tecOWNERS : 132,
|
||||
tecNO_ISSUER : 133,
|
||||
tecNO_AUTH : 134,
|
||||
tecNO_LINE : 135,
|
||||
tecINSUFF_FEE : 136,
|
||||
tecFROZEN : 137,
|
||||
tecNO_TARGET : 138,
|
||||
tecNO_PERMISSION : 139,
|
||||
tecNO_ENTRY : 140,
|
||||
tecINSUFFICIENT_RESERVE : 141,
|
||||
tecNEED_MASTER_KEY : 142,
|
||||
tecDST_TAG_NEEDED : 143,
|
||||
tecINTERNAL : 144
|
||||
};
|
||||
|
||||
@@ -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) {
|
||||
|
||||
333
src/js/ripple/crypt.js
Normal file
333
src/js/ripple/crypt.js
Normal file
@@ -0,0 +1,333 @@
|
||||
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));
|
||||
};
|
||||
|
||||
/**
|
||||
* add entropy at each call to get random words
|
||||
* @param {number} nWords
|
||||
*/
|
||||
function randomWords (nWords) {
|
||||
for (var i = 0; i < 8; i++) {
|
||||
sjcl.random.addEntropy(Math.random(), 32, "Math.random()");
|
||||
}
|
||||
|
||||
return sjcl.random.randomWords(nWords);
|
||||
}
|
||||
|
||||
/****** 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(randomWords(nWords));
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new master key
|
||||
*/
|
||||
|
||||
Crypt.createMaster = function () {
|
||||
return base.encode_check(33, sjcl.codec.bytes.fromBits(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;
|
||||
};
|
||||
|
||||
/**
|
||||
* base64 to UTF8
|
||||
*/
|
||||
|
||||
Crypt.decodeBase64 = function (data) {
|
||||
return sjcl.codec.utf8String.fromBits(sjcl.codec.base64.toBits(data));
|
||||
}
|
||||
|
||||
exports.Crypt = Crypt;
|
||||
@@ -1,15 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
var extend = require('extend');
|
||||
|
||||
var extend = require('extend');
|
||||
var UInt160 = require('./uint160').UInt160;
|
||||
var Float = require('./float').Float;
|
||||
var utils = require('./utils');
|
||||
var Float = require('./ieee754').Float;
|
||||
|
||||
//
|
||||
// Currency support
|
||||
//
|
||||
|
||||
var Currency = extend(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.
|
||||
|
||||
@@ -18,58 +18,174 @@ var Currency = extend(function () {
|
||||
// 3-letter code: ...
|
||||
// XXX Should support hex, C++ doesn't currently allow it.
|
||||
|
||||
this._value = NaN;
|
||||
|
||||
this._value = NaN;
|
||||
this._update();
|
||||
}, UInt160);
|
||||
|
||||
Currency.prototype = extend({}, UInt160.prototype);
|
||||
Currency.prototype.constructor = Currency;
|
||||
|
||||
Currency.HEX_CURRENCY_BAD = "0000000000000000000000005852500000000000";
|
||||
Currency.HEX_CURRENCY_BAD = '0000000000000000000000005852500000000000';
|
||||
|
||||
Currency.from_json = function (j, shouldInterpretXrpAsIou) {
|
||||
if (j instanceof this) {
|
||||
return j.clone();
|
||||
} else {
|
||||
return (new this()).parse_json(j, shouldInterpretXrpAsIou);
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
*/
|
||||
|
||||
/*eslint-disable max-len*/
|
||||
Currency.prototype.human_RE = /^\s*([a-zA-Z0-9\<\>\(\)\{\}\[\]\|\?\!\@\#\$\%\^\&]{3})(\s*-\s*[- \w]+)?(\s*\(-?\d+\.?\d*%pa\))?\s*$/;
|
||||
/*eslint-enable max-len*/
|
||||
|
||||
Currency.from_json = function(j, shouldInterpretXrpAsIou) {
|
||||
return (new Currency()).parse_json(j, shouldInterpretXrpAsIou);
|
||||
};
|
||||
|
||||
Currency.from_human = function(j, opts) {
|
||||
return (new Currency().parse_human(j, opts));
|
||||
};
|
||||
|
||||
// this._value = NaN on error.
|
||||
Currency.prototype.parse_json = function (j, shouldInterpretXrpAsIou) {
|
||||
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);
|
||||
}
|
||||
} else if (/^[a-zA-Z0-9]{3}$/.test(j)) {
|
||||
var currencyCode = j.toUpperCase();
|
||||
var currencyData = utils.arraySet(20, 0);
|
||||
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;
|
||||
if (j instanceof Currency) {
|
||||
this._value = j.copyTo({})._value;
|
||||
this._update();
|
||||
return this;
|
||||
}
|
||||
|
||||
switch (typeof j) {
|
||||
case 'number':
|
||||
if (!isNaN(j)) {
|
||||
this.parse_number(j);
|
||||
}
|
||||
break;
|
||||
case 'string':
|
||||
if (!j || j === '0') {
|
||||
// Empty string or XRP
|
||||
this.parse_hex(shouldInterpretXrpAsIou
|
||||
? Currency.HEX_CURRENCY_BAD
|
||||
: Currency.HEX_ZERO);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'object':
|
||||
if (j instanceof Currency) {
|
||||
this._value = j.copyTo({})._value;
|
||||
this._update();
|
||||
if (j === '1') {
|
||||
// 'no currency'
|
||||
this.parse_hex(Currency.HEX_ONE);
|
||||
break;
|
||||
}
|
||||
|
||||
if (/^[A-F0-9]{40}$/.test(j)) {
|
||||
// Hex format
|
||||
this.parse_hex(j);
|
||||
break;
|
||||
}
|
||||
|
||||
// match the given string to see if it's in an allowed format
|
||||
var matches = j.match(this.human_RE);
|
||||
|
||||
if (matches) {
|
||||
var currencyCode = matches[1];
|
||||
|
||||
// for the currency 'XRP' case
|
||||
// we drop everything else that could have been provided
|
||||
// e.g. 'XRP - Ripple'
|
||||
if (!currencyCode || /^(0|XRP)$/.test(currencyCode)) {
|
||||
this.parse_hex(shouldInterpretXrpAsIou
|
||||
? Currency.HEX_CURRENCY_BAD
|
||||
: Currency.HEX_ZERO);
|
||||
|
||||
// early break, we can't have interest on XRP
|
||||
break;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -77,29 +193,35 @@ Currency.prototype.parse_json = function (j, shouldInterpretXrpAsIou) {
|
||||
return this;
|
||||
};
|
||||
|
||||
Currency.prototype.parse_human = function(j) {
|
||||
return this.parse_json(j);
|
||||
};
|
||||
|
||||
/**
|
||||
* Recalculate internal representation.
|
||||
*
|
||||
* You should never need to call this.
|
||||
*/
|
||||
Currency.prototype._update = function () {
|
||||
|
||||
Currency.prototype._update = function() {
|
||||
var bytes = this.to_bytes();
|
||||
|
||||
// is it 0 everywhere except 12, 13, 14?
|
||||
var isZeroExceptInStandardPositions = true;
|
||||
|
||||
if (!bytes) {
|
||||
return "XRP";
|
||||
return;
|
||||
}
|
||||
|
||||
this._native = false;
|
||||
this._type = -1;
|
||||
this._interest_start = new Date();
|
||||
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);
|
||||
for (var i = 0; i < 20; i++) {
|
||||
isZeroExceptInStandardPositions = isZeroExceptInStandardPositions
|
||||
&& (i === 12 || i === 13 || i === 14 || bytes[i] === 0);
|
||||
}
|
||||
|
||||
if (isZeroExceptInStandardPositions) {
|
||||
@@ -107,9 +229,9 @@ Currency.prototype._update = function () {
|
||||
+ String.fromCharCode(bytes[13])
|
||||
+ String.fromCharCode(bytes[14]);
|
||||
|
||||
if (this._iso_code === "\0\0\0") {
|
||||
if (this._iso_code === '\u0000\u0000\u0000') {
|
||||
this._native = true;
|
||||
this._iso_code = "XRP";
|
||||
this._iso_code = 'XRP';
|
||||
}
|
||||
|
||||
this._type = 0;
|
||||
@@ -121,31 +243,32 @@ Currency.prototype._update = function () {
|
||||
this._type = 1;
|
||||
this._interest_start = (bytes[4] << 24) +
|
||||
(bytes[5] << 16) +
|
||||
(bytes[6] << 8) +
|
||||
(bytes[7] );
|
||||
this._interest_period = Float.fromBytes(bytes.slice(8, 16));
|
||||
(bytes[6] << 8) +
|
||||
(bytes[7]);
|
||||
this._interest_period = Float.fromIEEE754Double(bytes.slice(8, 16));
|
||||
}
|
||||
};
|
||||
|
||||
// XXX Probably not needed anymore?
|
||||
/*
|
||||
Currency.prototype.parse_bytes = function (byte_array) {
|
||||
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)
|
||||
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" ) {
|
||||
if (/^[A-Z0-9]{3}$/.test(currencyCode) && currencyCode !== 'XRP' ) {
|
||||
this._value = currencyCode;
|
||||
} else if (currencyCode === "\0\0\0") {
|
||||
} else if (currencyCode === '\0\0\0') {
|
||||
this._value = 0;
|
||||
} else {
|
||||
this._value = NaN;
|
||||
@@ -161,25 +284,58 @@ Currency.prototype.parse_bytes = function (byte_array) {
|
||||
};
|
||||
*/
|
||||
|
||||
Currency.prototype.is_native = function () {
|
||||
Currency.prototype.is_native = function() {
|
||||
return this._native;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this currency is an interest-bearing/demurring currency.
|
||||
* @return {Boolean} whether this currency is an interest-bearing currency
|
||||
*/
|
||||
Currency.prototype.has_interest = function () {
|
||||
return this._type === 1 && this._interest_start && !isNaN(this._interest_period);
|
||||
|
||||
Currency.prototype.has_interest = function() {
|
||||
return this._type === 1
|
||||
&& !isNaN(this._interest_start)
|
||||
&& !isNaN(this._interest_period);
|
||||
};
|
||||
|
||||
Currency.prototype.get_interest_at = function (referenceDate) {
|
||||
if (!this.has_interest) return 1;
|
||||
/**
|
||||
*
|
||||
* @param {number} 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) {
|
||||
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());
|
||||
}
|
||||
|
||||
return Math.pow(Math.E, (referenceDate - this._interest_start) / this._interest_period);
|
||||
// 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
|
||||
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.
|
||||
@@ -187,44 +343,60 @@ Currency.prototype.get_interest_at = function (referenceDate) {
|
||||
// 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.is_valid = function() {
|
||||
// return UInt.prototype.is_valid() && ...;
|
||||
// };
|
||||
|
||||
Currency.prototype.to_json = function () {
|
||||
Currency.prototype.to_json = function(opts) {
|
||||
if (!this.is_valid()) {
|
||||
// XXX This is backwards compatible behavior, but probably not very good.
|
||||
return "XRP";
|
||||
return 'XRP';
|
||||
}
|
||||
|
||||
// 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()) {
|
||||
return this._iso_code;
|
||||
if (!opts) {
|
||||
opts = {};
|
||||
}
|
||||
|
||||
// Fallback to returning the raw currency hex
|
||||
var currencyHex = this.to_hex();
|
||||
var currency;
|
||||
var fullName = opts && opts.full_name ? ' - ' + opts.full_name : '';
|
||||
opts.show_interest = opts.show_interest !== undefined
|
||||
? opts.show_interest
|
||||
: this.has_interest();
|
||||
|
||||
// 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 (currencyHex === Currency.HEX_ONE) {
|
||||
return 1;
|
||||
if (!opts.force_hex && /^[A-Z0-9]{3}$/.test(this._iso_code)) {
|
||||
currency = this._iso_code + fullName;
|
||||
if (opts.show_interest) {
|
||||
var decimals = !isNaN(opts.decimals) ? opts.decimals : undefined;
|
||||
var interestPercentage = this.has_interest()
|
||||
? this.get_interest_percentage_at(
|
||||
this._interest_start + 3600 * 24 * 365, decimals
|
||||
)
|
||||
: 0;
|
||||
currency += ' (' + interestPercentage + '%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 currencyHex;
|
||||
return currency;
|
||||
};
|
||||
|
||||
Currency.prototype.to_human = function () {
|
||||
Currency.prototype.to_human = function(opts) {
|
||||
// to_human() will always print the human-readable currency code if available.
|
||||
if (/^[A-Z0-9]{3}$/.test(this._iso_code)) {
|
||||
return this._iso_code;
|
||||
}
|
||||
return this.to_json(opts);
|
||||
};
|
||||
|
||||
return this.to_json();
|
||||
Currency.prototype.get_iso = function() {
|
||||
return this._iso_code;
|
||||
};
|
||||
|
||||
exports.Currency = Currency;
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
|
||||
@@ -8,12 +8,17 @@ var Float = exports.Float = {};
|
||||
var allZeros = /^0+$/;
|
||||
var allOnes = /^1+$/;
|
||||
|
||||
Float.fromBytes = function (bytes) {
|
||||
Float.fromBytes = function(bytes) {
|
||||
// Render in binary. Hackish.
|
||||
var b = "";
|
||||
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;
|
||||
|
||||
while (bits.length < 8) {
|
||||
bits = '0' + bits;
|
||||
}
|
||||
|
||||
b += bits;
|
||||
}
|
||||
|
||||
@@ -29,13 +34,11 @@ Float.fromBytes = function (bytes) {
|
||||
var m = b.substring(exponentBits + 1);
|
||||
|
||||
var value = 0;
|
||||
var multiplier = (s === "0" ? 1 : -1);
|
||||
var multiplier = (s === '0' ? 1 : -1);
|
||||
|
||||
if (allZeros.test(e)) {
|
||||
// Zero or denormalized
|
||||
if (allZeros.test(m)) {
|
||||
// Value is zero
|
||||
} else {
|
||||
if (!allZeros.test(m)) {
|
||||
value = parseInt(m, 2) * Math.pow(2, minExponent);
|
||||
}
|
||||
} else if (allOnes.test(e)) {
|
||||
|
||||
@@ -17,6 +17,8 @@ exports.HASH_TX_ID = 0x54584E00; // 'TXN'
|
||||
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)
|
||||
|
||||
107
src/js/ripple/ieee754.js
Normal file
107
src/js/ripple/ieee754.js
Normal 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")
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
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;
|
||||
'use strict';
|
||||
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.UInt128 = require('./uint128').UInt128;
|
||||
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.binformat = require('./binformat');
|
||||
exports.utils = require('./utils');
|
||||
exports.Server = require('./server').Server;
|
||||
exports.RippleError = require('./rippleerror').RippleError;
|
||||
exports.Message = require('./message').Message;
|
||||
exports.binformat = require('./binformat');
|
||||
exports.utils = require('./utils');
|
||||
exports.Server = require('./server').Server;
|
||||
exports.Wallet = require('./wallet');
|
||||
exports.Ledger = require('./ledger').Ledger;
|
||||
exports.TransactionQueue = require('./transactionqueue').TransactionQueue;
|
||||
exports.RangeSet = require('./rangeset').RangeSet;
|
||||
exports.convertBase = require('./baseconverter');
|
||||
|
||||
// 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
|
||||
@@ -23,32 +30,35 @@ exports.Server = require('./server').Server;
|
||||
// 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('./utils').sjcl;
|
||||
exports.sjcl = require('./utils').sjcl;
|
||||
exports.types = require('./serializedtypes');
|
||||
|
||||
exports.config = require('./config');
|
||||
|
||||
// camelCase to under_scored API conversion
|
||||
function attachUnderscored(c) {
|
||||
var o = exports[c];
|
||||
function attachUnderscored(name) {
|
||||
var o = exports[name];
|
||||
|
||||
Object.keys(o.prototype).forEach(function(key) {
|
||||
var UPPERCASE = /([A-Z]{1})[a-z]+/g;
|
||||
Object.keys(o.prototype).forEach(function(key) {
|
||||
var UPPERCASE = /([A-Z]{1})[a-z]+/g;
|
||||
|
||||
if (!UPPERCASE.test(key)) return;
|
||||
if (!UPPERCASE.test(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var underscored = key.replace(UPPERCASE, function(c) {
|
||||
return '_' + c.toLowerCase();
|
||||
});
|
||||
var underscored = key.replace(UPPERCASE, function(c) {
|
||||
return '_' + c.toLowerCase();
|
||||
});
|
||||
|
||||
o.prototype[underscored] = o.prototype[key];
|
||||
});
|
||||
};
|
||||
o.prototype[underscored] = o.prototype[key];
|
||||
});
|
||||
}
|
||||
|
||||
[ 'Remote',
|
||||
'Request',
|
||||
'Transaction',
|
||||
'Account',
|
||||
'Server'
|
||||
['Remote',
|
||||
'Request',
|
||||
'Transaction',
|
||||
'Account',
|
||||
'Server'
|
||||
].forEach(attachUnderscored);
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
|
||||
@@ -5,17 +5,17 @@ var UInt256 = require('./uint256').UInt256;
|
||||
var Base = require('./base').Base;
|
||||
|
||||
function KeyPair() {
|
||||
this._curve = sjcl.ecc.curves['c256'];
|
||||
this._curve = sjcl.ecc.curves.k256;
|
||||
this._secret = null;
|
||||
this._pubkey = null;
|
||||
};
|
||||
|
||||
KeyPair.from_bn_secret = function (j) {
|
||||
return j instanceof this ? j.clone() : (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.k256, j);
|
||||
return this;
|
||||
};
|
||||
|
||||
@@ -24,7 +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) {
|
||||
@@ -40,7 +40,7 @@ KeyPair.prototype._pub = function () {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
KeyPair.prototype._pub_bits = function () {
|
||||
KeyPair.prototype._pub_bits = function() {
|
||||
var pub = this._pub();
|
||||
|
||||
if (!pub) {
|
||||
@@ -60,7 +60,7 @@ KeyPair.prototype._pub_bits = function () {
|
||||
*
|
||||
* Key will be returned as a compressed pubkey - 33 bytes converted to hex.
|
||||
*/
|
||||
KeyPair.prototype.to_hex_pub = function () {
|
||||
KeyPair.prototype.to_hex_pub = function() {
|
||||
var bits = this._pub_bits();
|
||||
|
||||
if (!bits) {
|
||||
@@ -74,7 +74,7 @@ function SHA256_RIPEMD160(bits) {
|
||||
return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
|
||||
}
|
||||
|
||||
KeyPair.prototype.get_address = function () {
|
||||
KeyPair.prototype.get_address = function() {
|
||||
var bits = this._pub_bits();
|
||||
|
||||
if (!bits) {
|
||||
@@ -88,9 +88,11 @@ KeyPair.prototype.get_address = function () {
|
||||
return address;
|
||||
};
|
||||
|
||||
KeyPair.prototype.sign = function (hash) {
|
||||
var hash = UInt256.from_json(hash);
|
||||
return this._secret.signDER(hash.to_bits(), 0);
|
||||
KeyPair.prototype.sign = function(hash) {
|
||||
hash = UInt256.from_json(hash);
|
||||
var sig = this._secret.sign(hash.to_bits(), 0);
|
||||
sig = this._secret.canonicalizeSignature(sig);
|
||||
return this._secret.encodeDER(sig);
|
||||
};
|
||||
|
||||
exports.KeyPair = KeyPair;
|
||||
|
||||
@@ -5,6 +5,11 @@ 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()
|
||||
{
|
||||
@@ -17,6 +22,91 @@ Ledger.from_json = function (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;
|
||||
};
|
||||
@@ -37,4 +127,41 @@ Ledger.prototype.calc_tx_hash = function () {
|
||||
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;
|
||||
|
||||
22
src/js/ripple/ledgerspaces.js
Normal file
22
src/js/ripple/ledgerspaces.js
Normal 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'
|
||||
};
|
||||
@@ -1,17 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Logging functionality for ripple-lib and any applications built on it.
|
||||
*
|
||||
* @param {String} namespace logging prefix
|
||||
* @return {Void} this function does not return...
|
||||
*/
|
||||
var Log = function (namespace) {
|
||||
function Log(namespace) {
|
||||
if (!namespace) {
|
||||
this._namespace = [];
|
||||
} else if (Array.isArray(namespace)) {
|
||||
this._namespace = namespace;
|
||||
} else {
|
||||
this._namespace = [""+namespace];
|
||||
this._namespace = [String(namespace)];
|
||||
}
|
||||
|
||||
this._prefix = this._namespace.concat(['']).join(': ');
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a sub-logger.
|
||||
@@ -23,53 +28,112 @@ var Log = function (namespace) {
|
||||
* var log = require('ripple').log.sub('server');
|
||||
*
|
||||
* log.info('connection successful');
|
||||
* // prints: "server: connection successful"
|
||||
* // prints: 'server: connection successful'
|
||||
*
|
||||
* @param {String} namespace logging prefix
|
||||
* @return {Log} sub logger
|
||||
*/
|
||||
Log.prototype.sub = function (namespace) {
|
||||
Log.prototype.sub = function(namespace) {
|
||||
var subNamespace = this._namespace.slice();
|
||||
if (namespace && "string" === typeof namespace) subNamespace.push(namespace);
|
||||
|
||||
if (namespace && typeof namespace === 'string') {
|
||||
subNamespace.push(namespace);
|
||||
}
|
||||
|
||||
var subLogger = new Log(subNamespace);
|
||||
subLogger._setParent(this);
|
||||
return subLogger;
|
||||
};
|
||||
|
||||
Log.prototype._setParent = function (parentLogger) {
|
||||
Log.prototype._setParent = function(parentLogger) {
|
||||
this._parent = parentLogger;
|
||||
};
|
||||
|
||||
Log.makeLevel = function (level) {
|
||||
return function () {
|
||||
arguments[0] = this._prefix + arguments[0];
|
||||
|
||||
Log.engine.logObject.apply(Log, Array.prototype.slice.call(arguments));
|
||||
Log.makeLevel = function(level) {
|
||||
return function() {
|
||||
var args = Array.prototype.slice.apply(arguments);
|
||||
args[0] = this._prefix + args[0];
|
||||
Log.engine.logObject.apply(Log, [level].concat(args[0], [args.slice(2)]));
|
||||
};
|
||||
};
|
||||
|
||||
Log.prototype.debug = Log.makeLevel(1);
|
||||
Log.prototype.info = Log.makeLevel(2);
|
||||
Log.prototype.warn = Log.makeLevel(3);
|
||||
Log.prototype.info = Log.makeLevel(2);
|
||||
Log.prototype.warn = Log.makeLevel(3);
|
||||
Log.prototype.error = Log.makeLevel(4);
|
||||
|
||||
/**
|
||||
* @param {String} message
|
||||
* @param {Array} details
|
||||
* @return {Array} prepared log info
|
||||
*/
|
||||
|
||||
function getLogInfo(message, args) {
|
||||
return [
|
||||
// Timestamp
|
||||
'[' + new Date().toISOString() + ']',
|
||||
message,
|
||||
'--',
|
||||
// Location
|
||||
(new Error()).stack.split('\n')[4].replace(/^\s+/, ''),
|
||||
'\n'
|
||||
].concat(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Number} log level
|
||||
* @param {Array} log info
|
||||
*/
|
||||
|
||||
function logMessage(logLevel, args) {
|
||||
switch (logLevel) {
|
||||
case 1:
|
||||
case 2:
|
||||
console.log.apply(console, args);
|
||||
break;
|
||||
case 3:
|
||||
console.warn.apply(console, args);
|
||||
break;
|
||||
case 4:
|
||||
console.error.apply(console, args);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic logging connector.
|
||||
*
|
||||
* This engine has no formatting and works with the most basic of "console.log"
|
||||
* 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);
|
||||
|
||||
logObject: function logObject(level, message, args) {
|
||||
args = args.map(function(arg) {
|
||||
return JSON.stringify(arg, null, 2);
|
||||
});
|
||||
|
||||
args.unshift(msg);
|
||||
|
||||
console.log.apply(console, args);
|
||||
logMessage(level, getLogInfo(message, args));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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(level, message, args) {
|
||||
args = args.map(function(arg) {
|
||||
return /MSIE/.test(navigator.userAgent)
|
||||
? JSON.stringify(arg, null, 2)
|
||||
: arg;
|
||||
});
|
||||
|
||||
logMessage(level, getLogInfo(message, args));
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Null logging connector.
|
||||
*
|
||||
@@ -77,12 +141,16 @@ var BasicLogEngine = {
|
||||
* available.
|
||||
*/
|
||||
var NullLogEngine = {
|
||||
logObject: function () {}
|
||||
logObject: function() {}
|
||||
};
|
||||
|
||||
Log.engine = NullLogEngine;
|
||||
|
||||
if (console && console.log) Log.engine = BasicLogEngine;
|
||||
if (typeof window !== 'undefined' && typeof console !== 'undefined') {
|
||||
Log.engine = InteractiveLogEngine;
|
||||
} else if (typeof console !== 'undefined' && console.log) {
|
||||
Log.engine = BasicLogEngine;
|
||||
} else {
|
||||
Log.engine = NullLogEngine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a root logger as our main export.
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
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
203
src/js/ripple/message.js
Normal 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;
|
||||
@@ -1,51 +1,64 @@
|
||||
var extend = require('extend');
|
||||
var utils = require('./utils');
|
||||
var utils = require('./utils');
|
||||
var UInt160 = require('./uint160').UInt160;
|
||||
var Amount = require('./amount').Amount;
|
||||
|
||||
/**
|
||||
* Meta data processing facility
|
||||
*
|
||||
* @constructor
|
||||
* @param {Object} transaction metadata
|
||||
*/
|
||||
|
||||
function Meta(raw_data) {
|
||||
function Meta(data) {
|
||||
var self = this;
|
||||
|
||||
this.nodes = [ ];
|
||||
|
||||
raw_data.AffectedNodes.forEach(function(an) {
|
||||
var result = { };
|
||||
if (typeof data !== 'object') {
|
||||
throw new TypeError('Missing metadata');
|
||||
}
|
||||
|
||||
if (result.diffType = self.diffType(an)) {
|
||||
an = an[result.diffType];
|
||||
if (!Array.isArray(data.AffectedNodes)) {
|
||||
throw new TypeError('Metadata missing AffectedNodes');
|
||||
}
|
||||
|
||||
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 || {};
|
||||
|
||||
// getAffectedBooks will set this
|
||||
// result.bookKey = undefined;
|
||||
|
||||
self.nodes.push(result);
|
||||
}
|
||||
});
|
||||
data.AffectedNodes.forEach(this.addNode, this);
|
||||
};
|
||||
|
||||
Meta.node_types = [
|
||||
Meta.NODE_TYPES = [
|
||||
'CreatedNode',
|
||||
'ModifiedNode',
|
||||
'DeletedNode'
|
||||
];
|
||||
|
||||
Meta.prototype.diffType = function(an) {
|
||||
var result = false;
|
||||
Meta.AMOUNT_FIELDS_AFFECTING_ISSUER = [
|
||||
'LowLimit',
|
||||
'HighLimit',
|
||||
'TakerPays',
|
||||
'TakerGets'
|
||||
];
|
||||
|
||||
for (var i=0; i<Meta.node_types.length; i++) {
|
||||
var x = Meta.node_types[i];
|
||||
if (an.hasOwnProperty(x)) {
|
||||
result = x;
|
||||
Meta.ACCOUNT_FIELDS = [
|
||||
'Account',
|
||||
'Owner',
|
||||
'Destination',
|
||||
'Issuer',
|
||||
'Target'
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {Object} node
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Meta.prototype.getNodeType = function(node) {
|
||||
var result = null;
|
||||
|
||||
for (var i=0; i<Meta.NODE_TYPES.length; i++) {
|
||||
var type = Meta.NODE_TYPES[i];
|
||||
if (node.hasOwnProperty(type)) {
|
||||
result = type;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -53,6 +66,149 @@ Meta.prototype.diffType = function(an) {
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {String} field
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Meta.prototype.isAccountField = function(field) {
|
||||
return Meta.ACCOUNT_FIELDS.indexOf(field) !== -1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add node to metadata
|
||||
*
|
||||
* @param {Object} node
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Meta.prototype.addNode = function(node) {
|
||||
this._affectedAccounts = void(0);
|
||||
this._affectedBooks = void(0);
|
||||
|
||||
var result = { };
|
||||
|
||||
if ((result.nodeType = this.getNodeType(node))) {
|
||||
node = node[result.nodeType];
|
||||
result.diffType = result.nodeType;
|
||||
result.entryType = node.LedgerEntryType;
|
||||
result.ledgerIndex = node.LedgerIndex;
|
||||
result.fields = extend({ }, node.PreviousFields, node.NewFields, node.FinalFields);
|
||||
result.fieldsPrev = node.PreviousFields || { };
|
||||
result.fieldsNew = node.NewFields || { };
|
||||
result.fieldsFinal = node.FinalFields || { };
|
||||
|
||||
// getAffectedBooks will set this
|
||||
// result.bookKey = undefined;
|
||||
|
||||
this.nodes.push(result);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get affected nodes array
|
||||
*
|
||||
* @param {Object} filter options
|
||||
* @return {Array} nodes
|
||||
*/
|
||||
|
||||
Meta.prototype.getNodes = function(options) {
|
||||
if (typeof options === 'object') {
|
||||
return this.nodes.filter(function(node) {
|
||||
if (options.nodeType && options.nodeType !== node.nodeType) {
|
||||
return false;
|
||||
}
|
||||
if (options.entryType && options.entryType !== node.entryType) {
|
||||
return false;
|
||||
}
|
||||
if (options.bookKey && options.bookKey !== node.bookKey) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
} else {
|
||||
return this.nodes;
|
||||
}
|
||||
};
|
||||
|
||||
Meta.prototype.getAffectedAccounts = function(from) {
|
||||
if (this._affectedAccounts) {
|
||||
return this._affectedAccounts;
|
||||
}
|
||||
|
||||
var accounts = [ ];
|
||||
|
||||
// This code should match the behavior of the C++ method:
|
||||
// TransactionMetaSet::getAffectedAccounts
|
||||
for (var i=0; i<this.nodes.length; i++) {
|
||||
var node = this.nodes[i];
|
||||
var fields = (node.nodeType === 'CreatedNode')
|
||||
? node.fieldsNew
|
||||
: node.fieldsFinal;
|
||||
|
||||
for (var fieldName in fields) {
|
||||
var field = fields[fieldName];
|
||||
|
||||
if (this.isAccountField(fieldName) && UInt160.is_valid(field)) {
|
||||
accounts.push(field);
|
||||
} else if (~Meta.AMOUNT_FIELDS_AFFECTING_ISSUER.indexOf(fieldName)) {
|
||||
var amount = Amount.from_json(field);
|
||||
var issuer = amount.issuer();
|
||||
if (issuer.is_valid() && !issuer.is_zero()) {
|
||||
accounts.push(issuer.to_json());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._affectedAccounts = utils.arrayUnique(accounts);
|
||||
|
||||
return this._affectedAccounts;
|
||||
};
|
||||
|
||||
Meta.prototype.getAffectedBooks = function() {
|
||||
if (this._affectedBooks) {
|
||||
return this._affectedBooks;
|
||||
}
|
||||
|
||||
var books = [ ];
|
||||
|
||||
for (var i=0; i<this.nodes.length; i++) {
|
||||
var node = this.nodes[i];
|
||||
|
||||
if (node.entryType !== 'Offer') {
|
||||
continue;
|
||||
}
|
||||
|
||||
var gets = Amount.from_json(node.fields.TakerGets);
|
||||
var pays = Amount.from_json(node.fields.TakerPays);
|
||||
var getsKey = gets.currency().to_json();
|
||||
var paysKey = pays.currency().to_json();
|
||||
|
||||
if (getsKey !== 'XRP') {
|
||||
getsKey += '/' + gets.issuer().to_json();
|
||||
}
|
||||
|
||||
if (paysKey !== 'XRP') {
|
||||
paysKey += '/' + pays.issuer().to_json();
|
||||
}
|
||||
|
||||
var key = getsKey + ':' + paysKey;
|
||||
|
||||
// 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.
|
||||
node.bookKey = key;
|
||||
|
||||
books.push(key);
|
||||
}
|
||||
|
||||
this._affectedBooks = utils.arrayUnique(books);
|
||||
|
||||
return this._affectedBooks;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Execute a function on each affected node.
|
||||
*
|
||||
@@ -61,7 +217,7 @@ Meta.prototype.diffType = function(an) {
|
||||
*
|
||||
* {
|
||||
* // Type of diff, e.g. CreatedNode, ModifiedNode
|
||||
* diffType: 'CreatedNode'
|
||||
* nodeType: 'CreatedNode'
|
||||
*
|
||||
* // Type of node affected, e.g. RippleState, AccountRoot
|
||||
* entryType: 'RippleState',
|
||||
@@ -72,7 +228,7 @@ Meta.prototype.diffType = function(an) {
|
||||
* // Contains all fields with later versions taking precedence
|
||||
* //
|
||||
* // This is a shorthand for doing things like checking which account
|
||||
* // this affected without having to check the diffType.
|
||||
* // this affected without having to check the nodeType.
|
||||
* fields: {...},
|
||||
*
|
||||
* // Old fields (before the change)
|
||||
@@ -84,85 +240,21 @@ Meta.prototype.diffType = function(an) {
|
||||
* // Changed fields
|
||||
* fieldsFinal: {...}
|
||||
* }
|
||||
*
|
||||
* 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) {
|
||||
for (var i = 0, l = this.nodes.length; i < l; i++) {
|
||||
fn(this.nodes[i], i);
|
||||
}
|
||||
};
|
||||
|
||||
([
|
||||
[
|
||||
'forEach',
|
||||
'map',
|
||||
'filter',
|
||||
'every',
|
||||
'some',
|
||||
'reduce'
|
||||
]).forEach(function(fn) {
|
||||
].forEach(function(fn) {
|
||||
Meta.prototype[fn] = function() {
|
||||
return Array.prototype[fn].apply(this.nodes, arguments);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
var amountFieldsAffectingIssuer = [
|
||||
'LowLimit',
|
||||
'HighLimit',
|
||||
'TakerPays',
|
||||
'TakerGets'
|
||||
];
|
||||
|
||||
Meta.prototype.getAffectedAccounts = function () {
|
||||
var accounts = [ ];
|
||||
|
||||
// This code should match the behavior of the C++ method:
|
||||
// TransactionMetaSet::getAffectedAccounts
|
||||
this.nodes.forEach(function (an) {
|
||||
var fields = (an.diffType === 'CreatedNode') ? an.fieldsNew : an.fieldsFinal;
|
||||
for (var i in fields) {
|
||||
var field = fields[i];
|
||||
if (typeof field === 'string' && UInt160.is_valid(field)) {
|
||||
accounts.push(field);
|
||||
} else if (amountFieldsAffectingIssuer.indexOf(i) !== -1) {
|
||||
var amount = Amount.from_json(field);
|
||||
var issuer = amount.issuer();
|
||||
if (issuer.is_valid() && !issuer.is_zero()) {
|
||||
accounts.push(issuer.to_json());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return utils.arrayUnique(accounts);
|
||||
};
|
||||
|
||||
Meta.prototype.getAffectedBooks = function () {
|
||||
var books = [ ];
|
||||
|
||||
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();
|
||||
|
||||
var paysKey = pays.currency().to_json();
|
||||
if (paysKey !== 'XRP') paysKey += '/' + pays.issuer().to_json();
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
return utils.arrayUnique(books);
|
||||
};
|
||||
Meta.prototype.each = Meta.prototype.forEach;
|
||||
|
||||
exports.Meta = Meta;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -35,28 +35,27 @@ util.inherits(PathFind, EventEmitter);
|
||||
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);
|
||||
var req = this.remote.request_path_find_create(
|
||||
this.src_account,
|
||||
this.dst_account,
|
||||
this.dst_amount,
|
||||
this.src_currencies);
|
||||
|
||||
function handleInitialPath(err, msg) {
|
||||
if (err) {
|
||||
self.emit('error', err);
|
||||
} else {
|
||||
self.notify_update(msg);
|
||||
}
|
||||
}
|
||||
req.once('error', function(err) {
|
||||
self.emit('error', err);
|
||||
});
|
||||
req.once('success', function(msg) {
|
||||
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();
|
||||
req.broadcast().request();
|
||||
};
|
||||
|
||||
PathFind.prototype.close = function () {
|
||||
this.remote.request_path_find_close().request();
|
||||
this.remote.request_path_find_close().broadcast().request();
|
||||
this.emit('end');
|
||||
this.emit('close');
|
||||
};
|
||||
|
||||
67
src/js/ripple/rangeset.js
Normal file
67
src/js/ripple/rangeset.js
Normal file
@@ -0,0 +1,67 @@
|
||||
var assert = require('assert');
|
||||
var lodash = require('lodash');
|
||||
|
||||
function RangeSet() {
|
||||
this._ranges = [ ];
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a ledger range
|
||||
*
|
||||
* @param {Number|String} range string (n-n2,n3-n4)
|
||||
*/
|
||||
|
||||
RangeSet.prototype.add = function(range) {
|
||||
assert(typeof range !== 'number' || !isNaN(range), 'Ledger range malformed');
|
||||
|
||||
range = String(range).split(',');
|
||||
|
||||
if (range.length > 1) {
|
||||
return range.forEach(this.add, this);
|
||||
}
|
||||
|
||||
range = range[0].split('-').map(Number);
|
||||
|
||||
var lRange = {
|
||||
start: range[0],
|
||||
end: range[range.length === 1 ? 0 : 1]
|
||||
};
|
||||
|
||||
// Comparisons on NaN should be falsy
|
||||
assert(lRange.start <= lRange.end, 'Ledger range malformed');
|
||||
|
||||
var insertionPoint = lodash.sortedIndex(this._ranges, lRange, function(r) {
|
||||
return r.start;
|
||||
});
|
||||
|
||||
this._ranges.splice(insertionPoint, 0, lRange);
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* Check presence of ledger in range
|
||||
*
|
||||
* @param {Number|String} ledger
|
||||
* @return Boolean
|
||||
*/
|
||||
|
||||
RangeSet.prototype.has =
|
||||
RangeSet.prototype.contains = function(ledger) {
|
||||
assert(ledger != null && !isNaN(ledger), 'Ledger must be a number');
|
||||
|
||||
ledger = Number(ledger);
|
||||
|
||||
return this._ranges.some(function(r) {
|
||||
return ledger >= r.start && ledger <= r.end;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset ledger ranges
|
||||
*/
|
||||
|
||||
RangeSet.prototype.reset = function() {
|
||||
this._ranges = [ ];
|
||||
};
|
||||
|
||||
exports.RangeSet = RangeSet;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,10 @@
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var util = require('util');
|
||||
var async = require('async');
|
||||
var UInt160 = require('./uint160').UInt160;
|
||||
var Currency = require('./currency').Currency;
|
||||
var Transaction = require('./transaction').Transaction;
|
||||
var Account = require('./account').Account;
|
||||
var Meta = require('./meta').Meta;
|
||||
var OrderBook = require('./orderbook').OrderBook;
|
||||
var RippleError = require('./rippleerror').RippleError;
|
||||
var Server = require('./server').Server;
|
||||
|
||||
// Request events emitted:
|
||||
// 'success' : Request successful.
|
||||
@@ -14,37 +12,53 @@ var RippleError = require('./rippleerror').RippleError;
|
||||
// 'remoteError'
|
||||
// 'remoteUnexpected'
|
||||
// 'remoteDisconnected'
|
||||
|
||||
/**
|
||||
* Request
|
||||
*
|
||||
* @param {Remote} remote
|
||||
* @param {String} command
|
||||
*/
|
||||
|
||||
function Request(remote, command) {
|
||||
EventEmitter.call(this);
|
||||
|
||||
this.remote = remote;
|
||||
this.requested = false;
|
||||
this.message = {
|
||||
command : command,
|
||||
id : void(0)
|
||||
this.remote = remote;
|
||||
this.requested = false;
|
||||
this.reconnectTimeout = 1000 * 3;
|
||||
this.successEvent = 'success';
|
||||
this.errorEvent = 'error';
|
||||
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;
|
||||
Request.prototype.request = function(servers, callback) {
|
||||
this.emit('before');
|
||||
|
||||
if (typeof servers === 'function') {
|
||||
callback = servers;
|
||||
}
|
||||
|
||||
this.callback(callback);
|
||||
|
||||
if (this.requested) {
|
||||
return this;
|
||||
}
|
||||
|
||||
this.requested = true;
|
||||
this.on('error', new Function);
|
||||
this.emit('request', remote);
|
||||
this.on('error', function(){});
|
||||
this.emit('request', this.remote);
|
||||
|
||||
if (this._broadcast) {
|
||||
this.remote._servers.forEach(function(server) {
|
||||
if (Array.isArray(servers)) {
|
||||
servers.forEach(function(server) {
|
||||
this.setServer(server);
|
||||
this.remote.request(this);
|
||||
}, this );
|
||||
}, this);
|
||||
} else {
|
||||
this.remote.request(this);
|
||||
}
|
||||
@@ -52,25 +66,168 @@ Request.prototype.request = function(remote) {
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.callback = function(callback, successEvent, errorEvent) {
|
||||
if (callback && typeof callback === 'function') {
|
||||
var self = this;
|
||||
/**
|
||||
* Broadcast request to all servers, filter responses if a function is
|
||||
* provided. Return first response that satisfies the filter. Pre-filter
|
||||
* requests by ledger_index (if a ledger_index is set on the request), and
|
||||
* automatically retry servers when they reconnect--if they are expected to
|
||||
*
|
||||
* Whew
|
||||
*
|
||||
* @param [Function] fn
|
||||
*/
|
||||
|
||||
function request_success(message) {
|
||||
callback.call(self, null, message);
|
||||
Request.prototype.filter =
|
||||
Request.prototype.addFilter =
|
||||
Request.prototype.broadcast = function(filterFn) {
|
||||
var self = this;
|
||||
|
||||
if (!this.requested) {
|
||||
// Defer until requested, and prevent the normal request() from executing
|
||||
this.once('before', function() {
|
||||
self.requested = true;
|
||||
self.broadcast(filterFn);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
var filterFn = typeof filterFn === 'function' ? filterFn : Boolean;
|
||||
var lastResponse = new Error('No servers available');
|
||||
var connectTimeouts = { };
|
||||
var emit = this.emit;
|
||||
|
||||
this.emit = function(event, a, b) {
|
||||
// Proxy success/error events
|
||||
switch (event) {
|
||||
case 'success':
|
||||
case 'error':
|
||||
emit.call(self, 'proposed', a, b);
|
||||
break;
|
||||
default:
|
||||
emit.apply(self, arguments);
|
||||
}
|
||||
};
|
||||
|
||||
function iterator(server, callback) {
|
||||
// Iterator is called in parallel
|
||||
|
||||
if (server.isConnected()) {
|
||||
// Listen for proxied success/error event and apply filter
|
||||
self.once('proposed', function(res) {
|
||||
lastResponse = res;
|
||||
callback(filterFn(res));
|
||||
});
|
||||
|
||||
return server._request(self);
|
||||
}
|
||||
|
||||
function request_error(error) {
|
||||
// Server is disconnected but should reconnect. Wait for it to reconnect,
|
||||
// and abort after a timeout
|
||||
var serverID = server.getServerID();
|
||||
|
||||
function serverReconnected() {
|
||||
clearTimeout(connectTimeouts[serverID]);
|
||||
connectTimeouts[serverID] = null;
|
||||
iterator(server, callback);
|
||||
};
|
||||
|
||||
connectTimeouts[serverID] = setTimeout(function() {
|
||||
server.removeListener('connect', serverReconnected);
|
||||
callback(false);
|
||||
}, self.reconnectTimeout);
|
||||
|
||||
server.once('connect', serverReconnected);
|
||||
};
|
||||
|
||||
function complete(success) {
|
||||
// Emit success if the filter is satisfied by any server
|
||||
// Emit error if the filter is not satisfied by any server
|
||||
// Include the last response
|
||||
emit.call(self, success ? 'success' : 'error', lastResponse);
|
||||
};
|
||||
|
||||
var servers = this.remote._servers.filter(function(server) {
|
||||
// Pre-filter servers that are disconnected and should not reconnect
|
||||
return (server.isConnected() || server._shouldConnect)
|
||||
// Pre-filter servers that do not contain the ledger in request
|
||||
&& (!self.message.hasOwnProperty('ledger_index')
|
||||
|| server.hasLedger(self.message.ledger_index))
|
||||
&& (!self.message.hasOwnProperty('ledger_index_min')
|
||||
|| self.message.ledger_index_min === -1
|
||||
|| server.hasLedger(self.message.ledger_index_min))
|
||||
&& (!self.message.hasOwnProperty('ledger_index_max')
|
||||
|| self.message.ledger_index_max === -1
|
||||
|| server.hasLedger(self.message.ledger_index_max))
|
||||
});
|
||||
|
||||
// Apply iterator in parallel to connected servers, complete when the
|
||||
// supplied filter function is satisfied once by a server's response
|
||||
async.some(servers, iterator, complete);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.cancel = function() {
|
||||
this.removeAllListeners();
|
||||
this.on('error', function(){});
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.setCallback = function(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
this.callback(fn);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.setReconnectTimeout = function(timeout) {
|
||||
if (typeof timeout === 'number' && !isNaN(timeout)) {
|
||||
this.reconnectTimeout = timeout;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.callback = function(callback, successEvent, errorEvent) {
|
||||
var self = this;
|
||||
|
||||
if (typeof callback !== 'function') {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (typeof successEvent === 'string') {
|
||||
this.successEvent = successEvent;
|
||||
}
|
||||
if (typeof errorEvent === 'string') {
|
||||
this.errorEvent = errorEvent;
|
||||
}
|
||||
|
||||
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', request_success);
|
||||
this.once(errorEvent || 'error' , request_error);
|
||||
this.request();
|
||||
}
|
||||
this.once(this.successEvent, requestSuccess);
|
||||
this.once(this.errorEvent, requestError);
|
||||
this.request();
|
||||
|
||||
return this;
|
||||
};
|
||||
@@ -78,12 +235,13 @@ Request.prototype.callback = function(callback, successEvent, errorEvent) {
|
||||
Request.prototype.timeout = function(duration, callback) {
|
||||
var self = this;
|
||||
|
||||
function requested() {
|
||||
self.timeout(duration, callback);
|
||||
};
|
||||
|
||||
if (!this.requested) {
|
||||
function requested() {
|
||||
self.timeout(duration, callback);
|
||||
}
|
||||
this.once('request', requested);
|
||||
return;
|
||||
// Defer until requested
|
||||
return this.once('request', requested);
|
||||
}
|
||||
|
||||
var emit = this.emit;
|
||||
@@ -91,8 +249,13 @@ Request.prototype.timeout = function(duration, callback) {
|
||||
|
||||
var timeout = setTimeout(function() {
|
||||
timed_out = true;
|
||||
if (typeof callback === 'function') callback();
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
|
||||
emit.call(self, 'timeout');
|
||||
self.cancel();
|
||||
}, duration);
|
||||
|
||||
this.emit = function() {
|
||||
@@ -112,10 +275,13 @@ Request.prototype.setServer = function(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._host === server) {
|
||||
|
||||
for (var i=0, s; (s=servers[i]); i++) {
|
||||
if (s._url === server) {
|
||||
selected = s;
|
||||
break;
|
||||
}
|
||||
@@ -129,12 +295,11 @@ Request.prototype.setServer = function(server) {
|
||||
};
|
||||
|
||||
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' );
|
||||
'`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) {
|
||||
@@ -142,8 +307,9 @@ Request.prototype.buildPath = function(build) {
|
||||
} else {
|
||||
// ND: rippled currently intreprets the mere presence of `build_path` as the
|
||||
// value being `truthy`
|
||||
delete this.message.build_path
|
||||
delete this.message.build_path;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
@@ -153,6 +319,7 @@ Request.prototype.ledgerChoose = function(current) {
|
||||
} else {
|
||||
this.message.ledger_hash = this.remote._ledger_hash;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
@@ -171,19 +338,25 @@ Request.prototype.ledgerIndex = function(ledger_index) {
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.ledgerSelect = function(ledger_spec) {
|
||||
switch (ledger_spec) {
|
||||
/**
|
||||
* Set either ledger_index or ledger_hash based on heuristic
|
||||
*
|
||||
* @param {Number|String} ledger identifier
|
||||
*/
|
||||
|
||||
Request.prototype.selectLedger =
|
||||
Request.prototype.ledgerSelect = function(ledger) {
|
||||
switch (ledger) {
|
||||
case 'current':
|
||||
case 'closed':
|
||||
case 'verified':
|
||||
this.message.ledger_index = ledger_spec;
|
||||
case 'validated':
|
||||
this.message.ledger_index = ledger;
|
||||
break;
|
||||
|
||||
default:
|
||||
if (Number(ledger_spec)) {
|
||||
this.message.ledger_index = ledger_spec;
|
||||
} else {
|
||||
this.message.ledger_hash = ledger_spec;
|
||||
if (Number(ledger) && isFinite(Number(ledger))) {
|
||||
this.message.ledger_index = Number(ledger);
|
||||
} else if (/^[A-F0-9]{64}$/.test(ledger)) {
|
||||
this.message.ledger_hash = ledger;
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -192,12 +365,12 @@ Request.prototype.ledgerSelect = function(ledger_spec) {
|
||||
};
|
||||
|
||||
Request.prototype.accountRoot = function(account) {
|
||||
this.message.account_root = UInt160.json_rewrite(account);
|
||||
this.message.account_root = UInt160.json_rewrite(account);
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.index = function(hash) {
|
||||
this.message.index = hash;
|
||||
Request.prototype.index = function(index) {
|
||||
this.message.index = index;
|
||||
return this;
|
||||
};
|
||||
|
||||
@@ -206,44 +379,44 @@ Request.prototype.index = function(hash) {
|
||||
// --> seq : sequence number of transaction creating offer (integer)
|
||||
Request.prototype.offerId = function(account, sequence) {
|
||||
this.message.offer = {
|
||||
account: UInt160.json_rewrite(account),
|
||||
seq: sequence
|
||||
account: UInt160.json_rewrite(account),
|
||||
seq: sequence
|
||||
};
|
||||
return this;
|
||||
};
|
||||
|
||||
// --> index : ledger entry index.
|
||||
Request.prototype.offerIndex = function(index) {
|
||||
this.message.offer = index;
|
||||
this.message.offer = index;
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.secret = function(secret) {
|
||||
if (secret) {
|
||||
this.message.secret = secret;
|
||||
this.message.secret = secret;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.txHash = function(hash) {
|
||||
this.message.tx_hash = hash;
|
||||
this.message.tx_hash = hash;
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.txJson = function(json) {
|
||||
this.message.tx_json = json;
|
||||
this.message.tx_json = json;
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.txBlob = function(json) {
|
||||
this.message.tx_blob = json;
|
||||
this.message.tx_blob = json;
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.rippleState = function(account, issuer, currency) {
|
||||
this.message.ripple_state = {
|
||||
currency : currency,
|
||||
accounts : [
|
||||
this.message.ripple_state = {
|
||||
currency: currency,
|
||||
accounts: [
|
||||
UInt160.json_rewrite(account),
|
||||
UInt160.json_rewrite(issuer)
|
||||
]
|
||||
@@ -251,6 +424,7 @@ Request.prototype.rippleState = function(account, issuer, currency) {
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.setAccounts =
|
||||
Request.prototype.accounts = function(accounts, proposed) {
|
||||
if (!Array.isArray(accounts)) {
|
||||
accounts = [ accounts ];
|
||||
@@ -271,31 +445,39 @@ Request.prototype.accounts = function(accounts, proposed) {
|
||||
};
|
||||
|
||||
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);
|
||||
if (Array.isArray(account)) {
|
||||
account.forEach(this.addAccount, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
var processedAccount = UInt160.json_rewrite(account);
|
||||
var prop = proposed === true ? 'accounts_proposed' : 'accounts';
|
||||
this.message[prop] = (this.message[prop] || []).concat(processedAccount);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.setAccountsProposed =
|
||||
Request.prototype.rtAccounts =
|
||||
Request.prototype.accountsProposed = function(accounts) {
|
||||
return this.accounts(accounts, true);
|
||||
};
|
||||
|
||||
Request.prototype.addAccountProposed = function(account) {
|
||||
if (Array.isArray(account)) {
|
||||
account.forEach(this.addAccountProposed, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
return this.addAccount(account, true);
|
||||
};
|
||||
|
||||
Request.prototype.setBooks =
|
||||
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++) {
|
||||
for (var i=0, l=books.length; i<l; i++) {
|
||||
var book = books[i];
|
||||
this.addBook(book, snapshot);
|
||||
}
|
||||
@@ -303,9 +485,10 @@ Request.prototype.books = function(books, snapshot) {
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.addBook = function (book, snapshot) {
|
||||
if (!Array.isArray(this.message.books)) {
|
||||
this.message.books = [];
|
||||
Request.prototype.addBook = function(book, snapshot) {
|
||||
if (Array.isArray(book)) {
|
||||
book.forEach(this.addBook, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
var json = { };
|
||||
@@ -316,25 +499,64 @@ Request.prototype.addBook = function (book, snapshot) {
|
||||
}
|
||||
|
||||
var obj = json[side] = {
|
||||
currency: Currency.json_rewrite(book[side].currency)
|
||||
currency: Currency.json_rewrite(book[side].currency, { force_hex: true })
|
||||
};
|
||||
|
||||
if (obj.currency !== 'XRP') {
|
||||
if (!Currency.from_json(obj.currency).is_native()) {
|
||||
obj.issuer = UInt160.json_rewrite(book[side].issuer);
|
||||
}
|
||||
}
|
||||
|
||||
[ 'taker_gets', 'taker_pays' ].forEach(processSide);
|
||||
|
||||
if (snapshot) {
|
||||
if (typeof snapshot !== 'boolean') {
|
||||
json.snapshot = true;
|
||||
} else if (snapshot) {
|
||||
json.snapshot = true;
|
||||
} else {
|
||||
delete json.snapshot;
|
||||
}
|
||||
|
||||
if (book.both) {
|
||||
json.both = true;
|
||||
}
|
||||
|
||||
this.message.books.push(json);
|
||||
this.message.books = (this.message.books || []).concat(json);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Request.prototype.addStream = function(stream, values) {
|
||||
var self = this;
|
||||
|
||||
if (Array.isArray(values)) {
|
||||
switch (stream) {
|
||||
case 'accounts':
|
||||
this.addAccount(values);
|
||||
break;
|
||||
case 'accounts_proposed':
|
||||
this.addAccountProposed(values);
|
||||
break;
|
||||
case 'books':
|
||||
this.addBook(values);
|
||||
break;
|
||||
}
|
||||
} else if (arguments.length > 1) {
|
||||
for (arg in arguments) {
|
||||
this.addStream(arguments[arg]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Array.isArray(this.message.streams)) {
|
||||
this.message.streams = [ ];
|
||||
}
|
||||
|
||||
if (this.message.streams.indexOf(stream) === -1) {
|
||||
this.message.streams.push(stream);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
exports.Request = Request;
|
||||
|
||||
@@ -6,8 +6,9 @@ function RippleError(code, message) {
|
||||
case 'object':
|
||||
extend(this, code);
|
||||
break;
|
||||
|
||||
case 'string':
|
||||
this.result = code;
|
||||
this.result = code;
|
||||
this.result_message = message;
|
||||
break;
|
||||
}
|
||||
@@ -17,11 +18,13 @@ function RippleError(code, message) {
|
||||
this.result_message = this.message = (this.result_message);
|
||||
|
||||
var stack;
|
||||
if (!!Error.captureStackTrace)
|
||||
|
||||
if (!!Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, code || this);
|
||||
else if (stack = new Error().stack)
|
||||
} else if ((stack = new Error().stack)) {
|
||||
this.stack = stack;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
util.inherits(RippleError, Error);
|
||||
|
||||
|
||||
@@ -2,20 +2,18 @@
|
||||
// Seed support
|
||||
//
|
||||
|
||||
var utils = require('./utils');
|
||||
var sjcl = utils.sjcl;
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
var extend = require('extend');
|
||||
var utils = require('./utils');
|
||||
var sjcl = utils.sjcl;
|
||||
|
||||
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.k256;
|
||||
this._value = NaN;
|
||||
}, UInt);
|
||||
|
||||
@@ -30,10 +28,10 @@ Seed.prototype.parse_json = function (j) {
|
||||
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);
|
||||
} else if (/^[0-9a-fA-f]{32}$/.test(j)) {
|
||||
this.parse_hex(j);
|
||||
// XXX Should also try 1751
|
||||
} else {
|
||||
this.parse_passphrase(j);
|
||||
@@ -47,7 +45,7 @@ Seed.prototype.parse_json = function (j) {
|
||||
|
||||
Seed.prototype.parse_passphrase = function (j) {
|
||||
if (typeof j !== 'string') {
|
||||
throw new Error("Passphrase must be a string");
|
||||
throw new Error('Passphrase must be a string');
|
||||
}
|
||||
|
||||
var hash = sjcl.hash.sha512.hash(sjcl.codec.utf8String.toBits(j));
|
||||
@@ -59,7 +57,7 @@ Seed.prototype.parse_passphrase = function (j) {
|
||||
};
|
||||
|
||||
Seed.prototype.to_json = function () {
|
||||
if (!(this._value instanceof BigInteger)) {
|
||||
if (!(this.is_valid())) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
@@ -83,15 +81,39 @@ function SHA256_RIPEMD160(bits) {
|
||||
return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
|
||||
};
|
||||
|
||||
Seed.prototype.get_key = function (account_id) {
|
||||
/**
|
||||
* @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.
|
||||
*
|
||||
* @param maxLoops (optional)
|
||||
* {Number} specifies the amount of attempts taken to generate
|
||||
* a matching KeyPair
|
||||
*/
|
||||
Seed.prototype.get_key = function (account, maxLoops) {
|
||||
var account_number = 0, address;
|
||||
var max_loops = maxLoops || 1;
|
||||
|
||||
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;
|
||||
max_loops = account_number+1;
|
||||
} 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 seq = 0, i = 0;
|
||||
var i = 0;
|
||||
|
||||
do {
|
||||
private_gen = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(this.to_bytes(), i)));
|
||||
@@ -101,16 +123,30 @@ Seed.prototype.get_key = function (account_id) {
|
||||
public_gen = curve.G.mult(private_gen);
|
||||
|
||||
var sec;
|
||||
i = 0;
|
||||
var key_pair;
|
||||
|
||||
do {
|
||||
sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), seq), i)));
|
||||
i++;
|
||||
} while (!curve.r.greaterEquals(sec));
|
||||
|
||||
sec = sec.add(private_gen).mod(curve.r);
|
||||
i = 0;
|
||||
|
||||
return KeyPair.from_bn_secret(sec);
|
||||
do {
|
||||
sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), account_number), i)));
|
||||
i++;
|
||||
} while (!curve.r.greaterEquals(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;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
var binformat = require('./binformat');
|
||||
var extend = require('extend');
|
||||
var stypes = require('./serializedtypes');
|
||||
var UInt256 = require('./uint256').UInt256;
|
||||
var assert = require('assert');
|
||||
var _ = require('lodash');
|
||||
var assert = require('assert');
|
||||
var extend = require('extend');
|
||||
var binformat = require('./binformat');
|
||||
var stypes = require('./serializedtypes');
|
||||
var Crypt = require('./crypt').Crypt;
|
||||
var utils = require('./utils');
|
||||
|
||||
var utils = require('./utils');
|
||||
var sjcl = utils.sjcl;
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
var sjcl = utils.sjcl;
|
||||
|
||||
var TRANSACTION_TYPES = { };
|
||||
|
||||
@@ -26,6 +26,13 @@ Object.keys(binformat.ter).forEach(function(key) {
|
||||
TRANSACTION_RESULTS[binformat.ter[key]] = key;
|
||||
});
|
||||
|
||||
function normalize_sjcl_bn_hex(string) {
|
||||
var hex = string.slice(2); // remove '0x' prefix
|
||||
// now strip leading zeros
|
||||
var i = _.findIndex(hex, function(c) { return c !== '0'; });
|
||||
return i >= 0 ? hex.slice(i) : '0';
|
||||
}
|
||||
|
||||
function SerializedObject(buf) {
|
||||
if (Array.isArray(buf) || (Buffer && Buffer.isBuffer(buf)) ) {
|
||||
this.buffer = buf;
|
||||
@@ -37,35 +44,48 @@ function SerializedObject(buf) {
|
||||
throw new Error('Invalid buffer passed.');
|
||||
}
|
||||
this.pointer = 0;
|
||||
};
|
||||
}
|
||||
|
||||
SerializedObject.from_json = function (obj) {
|
||||
SerializedObject.from_json = function(obj) {
|
||||
// Create a copy of the object so we don't modify it
|
||||
var obj = extend({}, obj);
|
||||
var so = new SerializedObject;
|
||||
obj = extend(true, {}, 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.');
|
||||
}
|
||||
}
|
||||
|
||||
if ("string" === typeof obj.TransactionType) {
|
||||
typedef = binformat.tx[obj.TransactionType];
|
||||
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 if ("object" === typeof obj.AffectedNodes) {
|
||||
} 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' +
|
||||
@@ -79,49 +99,52 @@ SerializedObject.from_json = function (obj) {
|
||||
return so;
|
||||
};
|
||||
|
||||
SerializedObject.check_no_missing_fields = function (typedef, obj) {
|
||||
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 field = spec[0];
|
||||
var requirement = spec[1];
|
||||
|
||||
if (binformat.REQUIRED === requirement && obj[field] == null) {
|
||||
if (binformat.REQUIRED === requirement && obj[field] === void(0)) {
|
||||
missing_fields.push(field);
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (missing_fields.length > 0) {
|
||||
var object_name;
|
||||
if (obj.TransactionType != null) {
|
||||
object_name = SerializedObject.lookup_type_tx(obj.TransactionType);
|
||||
} else {
|
||||
object_name = "TransactionMetaData";
|
||||
} /*else {
|
||||
TODO: LedgerEntryType ...
|
||||
}*/
|
||||
throw new Error(object_name + " is missing fields: " +
|
||||
JSON.stringify(missing_fields));
|
||||
};
|
||||
}
|
||||
|
||||
SerializedObject.prototype.append = function (bytes) {
|
||||
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.resetPointer = function () {
|
||||
SerializedObject.prototype.resetPointer = function() {
|
||||
this.pointer = 0;
|
||||
};
|
||||
|
||||
function readOrPeek(advance) {
|
||||
return function(bytes) {
|
||||
var start = this.pointer;
|
||||
var end = start + bytes;
|
||||
var end = start + bytes;
|
||||
|
||||
if (end > this.buffer.length) {
|
||||
throw new Error('Buffer length exceeded');
|
||||
@@ -134,18 +157,18 @@ function readOrPeek(advance) {
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
SerializedObject.prototype.read = readOrPeek(true);
|
||||
|
||||
SerializedObject.prototype.peek = readOrPeek(false);
|
||||
|
||||
SerializedObject.prototype.to_bits = function () {
|
||||
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();
|
||||
};
|
||||
|
||||
@@ -164,7 +187,7 @@ SerializedObject.prototype.to_json = function() {
|
||||
this.pointer = old_pointer;
|
||||
|
||||
return output;
|
||||
}
|
||||
};
|
||||
|
||||
SerializedObject.jsonify_structure = function(structure, field_name) {
|
||||
var output;
|
||||
@@ -186,14 +209,20 @@ SerializedObject.jsonify_structure = function(structure, field_name) {
|
||||
}
|
||||
break;
|
||||
case 'object':
|
||||
if (!structure) break; //null
|
||||
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 if (structure instanceof sjcl.bn) {
|
||||
output = ('0000000000000000' + normalize_sjcl_bn_hex(structure.toString()).toUpperCase()).slice(-16);
|
||||
} else {
|
||||
output = new structure.constructor; //new Array or Object
|
||||
//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);
|
||||
@@ -207,7 +236,7 @@ SerializedObject.jsonify_structure = function(structure, field_name) {
|
||||
return output;
|
||||
};
|
||||
|
||||
SerializedObject.prototype.serialize = function (typedef, obj) {
|
||||
SerializedObject.prototype.serialize = function(typedef, obj) {
|
||||
// Serialize object without end marker
|
||||
stypes.Object.serialize(this, obj, true);
|
||||
|
||||
@@ -223,23 +252,26 @@ SerializedObject.prototype.serialize = function (typedef, obj) {
|
||||
*/
|
||||
};
|
||||
|
||||
SerializedObject.prototype.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);
|
||||
};
|
||||
|
||||
// DEPRECATED
|
||||
SerializedObject.prototype.signing_hash = SerializedObject.prototype.hash;
|
||||
|
||||
SerializedObject.prototype.hash_sha512_half = function () {
|
||||
var bits = sjcl.codec.bytes.toBits(this.buffer);
|
||||
var hash = sjcl.bitArray.bitSlice(sjcl.hash.sha512.hash(bits), 0, 256);
|
||||
return UInt256.from_hex(sjcl.codec.hex.fromBits(hash));
|
||||
};
|
||||
|
||||
SerializedObject.prototype.serialize_field = function (spec, obj) {
|
||||
SerializedObject.prototype.serialize_field = function(spec, obj) {
|
||||
var name = spec[0];
|
||||
var presence = spec[1];
|
||||
var field_id = spec[2];
|
||||
@@ -262,7 +294,7 @@ SerializedObject.prototype.serialize_field = function (spec, obj) {
|
||||
}
|
||||
};
|
||||
|
||||
SerializedObject.get_field_header = function (type_id, field_id) {
|
||||
SerializedObject.get_field_header = function(type_id, field_id) {
|
||||
var buffer = [ 0 ];
|
||||
|
||||
if (type_id > 0xF) {
|
||||
@@ -280,20 +312,25 @@ SerializedObject.get_field_header = function (type_id, field_id) {
|
||||
return buffer;
|
||||
};
|
||||
|
||||
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) {
|
||||
assert(typeof id === 'number');
|
||||
SerializedObject.lookup_type_tx = function(id) {
|
||||
assert.strictEqual(typeof id, 'number');
|
||||
return TRANSACTION_TYPES[id];
|
||||
};
|
||||
|
||||
SerializedObject.lookup_type_le = function (id) {
|
||||
assert(typeof id === 'number');
|
||||
return LEDGER_ENTRY_TYPES[id];
|
||||
};
|
||||
|
||||
exports.SerializedObject = SerializedObject;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -7,15 +7,15 @@ var UInt256 = require('./uint256').UInt256;
|
||||
var SerializedObject = require('./serializedobject').SerializedObject;
|
||||
|
||||
function SHAMap() {
|
||||
this.root = new SHAMapTreeNodeInner();
|
||||
this.root = new SHAMapTreeNodeInner(0);
|
||||
};
|
||||
|
||||
SHAMap.prototype.add_item = function (tag, node, type) {
|
||||
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 () {
|
||||
SHAMap.prototype.hash = function() {
|
||||
return this.root.hash();
|
||||
};
|
||||
|
||||
@@ -24,96 +24,100 @@ SHAMap.prototype.hash = function () {
|
||||
*
|
||||
* Can be either SHAMapTreeNodeInner or SHAMapTreeNodeLeaf.
|
||||
*/
|
||||
function SHAMapTreeNode() {
|
||||
|
||||
};
|
||||
function SHAMapTreeNode() { };
|
||||
|
||||
SHAMapTreeNode.TYPE_INNER = 1;
|
||||
SHAMapTreeNode.TYPE_TRANSACTION_NM = 2;
|
||||
SHAMapTreeNode.TYPE_TRANSACTION_MD = 3;
|
||||
SHAMapTreeNode.TYPE_ACCOUNT_STATE = 4;
|
||||
|
||||
SHAMapTreeNode.prototype.add_item = function (tag_segment, node) {
|
||||
throw new Error("Called unimplemented virtual method SHAMapTreeNode#add_item.");
|
||||
/**
|
||||
* @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.");
|
||||
SHAMapTreeNode.prototype.hash = function() {
|
||||
throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.');
|
||||
};
|
||||
|
||||
/**
|
||||
* Inner (non-leaf) node in a SHAMap tree.
|
||||
*/
|
||||
function SHAMapTreeNodeInner() {
|
||||
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);
|
||||
|
||||
SHAMapTreeNodeInner.prototype.add_item = function (tag_segment, node) {
|
||||
var current_node = this.get_node(tag_segment[0]);
|
||||
/**
|
||||
* @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 (current_node) {
|
||||
if (existing_node) {
|
||||
// A node already exists in this slot
|
||||
|
||||
if (current_node instanceof SHAMapTreeNodeInner) {
|
||||
if (existing_node instanceof SHAMapTreeNodeInner) {
|
||||
// There is an inner node, so we need to go deeper
|
||||
current_node.add_item(tag_segment.slice(1), node);
|
||||
} else if (current_node.get_segment() === tag_segment) {
|
||||
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.");
|
||||
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();
|
||||
var new_inner_node = new SHAMapTreeNodeInner(depth + 1);
|
||||
|
||||
// Move the existing leaf node down one level
|
||||
current_node.set_segment(current_node.get_segment().slice(1));
|
||||
new_inner_node.set_node(current_node.get_segment()[0], current_node);
|
||||
|
||||
// Add the new node next to it
|
||||
new_inner_node.add_item(tag_segment.slice(1), node);
|
||||
// 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_segment[0], new_inner_node);
|
||||
this.set_node(tag[depth], new_inner_node);
|
||||
}
|
||||
} else {
|
||||
// Neat, we have a nice open spot for the new node
|
||||
node.set_segment(tag_segment);
|
||||
this.set_node(tag_segment[0], node);
|
||||
this.set_node(tag[depth], node);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Overwrite the node that is currently in a given slot.
|
||||
*/
|
||||
SHAMapTreeNodeInner.prototype.set_node = function (slot, node) {
|
||||
SHAMapTreeNodeInner.prototype.set_node = function(slot, node) {
|
||||
this.leaves[slot] = node;
|
||||
this.empty = false;
|
||||
};
|
||||
|
||||
SHAMapTreeNodeInner.prototype.get_node = function (slot) {
|
||||
SHAMapTreeNodeInner.prototype.get_node = function(slot) {
|
||||
return this.leaves[slot];
|
||||
};
|
||||
|
||||
SHAMapTreeNodeInner.prototype.hash = function () {
|
||||
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 buffer = [ ];
|
||||
|
||||
for (var i=0; i<16; i++) {
|
||||
var leafHash = UInt256.from_hex(UInt256.HEX_ZERO);
|
||||
var slot = i.toString(16).toUpperCase();
|
||||
if ("object" === typeof this.leaves[slot]) {
|
||||
|
||||
if (typeof this.leaves[slot] === 'object') {
|
||||
leafHash = this.leaves[slot].hash();
|
||||
}
|
||||
|
||||
hash_buffer.append(leafHash.to_bytes());
|
||||
}
|
||||
|
||||
@@ -128,42 +132,33 @@ SHAMapTreeNodeInner.prototype.hash = function () {
|
||||
function SHAMapTreeNodeLeaf(tag, node, type) {
|
||||
SHAMapTreeNode.call(this);
|
||||
|
||||
if ("string" === typeof tag) {
|
||||
tag = UInt256.from_hex(tag);
|
||||
} else if (tag instanceof UInt256) {
|
||||
// Type is already the right one
|
||||
} else {
|
||||
throw new Error("Tag is unexpected type.");
|
||||
if (typeof tag !== 'string') {
|
||||
throw new Error('Tag is unexpected type.');
|
||||
}
|
||||
|
||||
this.tag = tag;
|
||||
this.tag_segment = null;
|
||||
|
||||
this.tag_bytes = UInt256.from_hex(this.tag).to_bytes();
|
||||
this.type = type;
|
||||
|
||||
this.node = node;
|
||||
}
|
||||
};
|
||||
|
||||
util.inherits(SHAMapTreeNodeLeaf, SHAMapTreeNode);
|
||||
|
||||
SHAMapTreeNodeLeaf.prototype.get_segment = function (segment) {
|
||||
return this.tag_segment;
|
||||
};
|
||||
|
||||
SHAMapTreeNodeLeaf.prototype.set_segment = function (segment) {
|
||||
this.tag_segment = segment;
|
||||
};
|
||||
|
||||
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;
|
||||
return this.tag_bytes;
|
||||
case SHAMapTreeNode.TYPE_TRANSACTION_MD:
|
||||
buffer.append(this.node);
|
||||
buffer.append(this.tag.to_bytes());
|
||||
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.");
|
||||
throw new Error('Tried to hash a SHAMap node of unknown type.');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,144 +1,164 @@
|
||||
'use strict';
|
||||
|
||||
var lodash = require('lodash');
|
||||
var LRU = require('lru-cache');
|
||||
var Transaction = require('./transaction').Transaction;
|
||||
|
||||
/**
|
||||
* Manager for pending transactions
|
||||
*/
|
||||
|
||||
var Transaction = require('./transaction').Transaction;
|
||||
|
||||
function TransactionQueue() {
|
||||
var self = this;
|
||||
|
||||
this._queue = [ ];
|
||||
this._idCache = { };
|
||||
this._sequenceCache = { };
|
||||
this._save = void(0);
|
||||
};
|
||||
|
||||
TransactionQueue.prototype.clearCache = function() {
|
||||
this._idCache = { };
|
||||
this._sequenceCache = { };
|
||||
};
|
||||
|
||||
TransactionQueue.prototype.getMinLedger = function() {
|
||||
var minLedger = Infinity;
|
||||
|
||||
for (var i=0; i<this._queue.length; i++) {
|
||||
var submitIndex = this._queue[i].submitIndex;
|
||||
|
||||
if (typeof submitIndex !== 'number') {
|
||||
// If any pending transactions don't have a submit index,
|
||||
// return -1 for scanning all previous transactions
|
||||
minLedger = -1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (submitIndex < minLedger) {
|
||||
minLedger = submitIndex;
|
||||
}
|
||||
};
|
||||
|
||||
if (!isFinite(minLedger)) minLedger = -1;
|
||||
|
||||
if (minLedger !== -1) minLedger -= 1;
|
||||
|
||||
return minLedger;
|
||||
};
|
||||
|
||||
TransactionQueue.prototype.save = function() {
|
||||
if (typeof this._save !== 'function') return;
|
||||
|
||||
this._save(this._queue.map(function(tx) {
|
||||
return {
|
||||
tx_json: tx.tx_json,
|
||||
submittedIDs: tx.submittedIDs
|
||||
}
|
||||
}));
|
||||
};
|
||||
this._queue = [ ];
|
||||
this._idCache = new LRU({max: 200});
|
||||
this._sequenceCache = new LRU({max: 200});
|
||||
}
|
||||
|
||||
/**
|
||||
* Store received (validated) sequence
|
||||
*
|
||||
* @param {Number} sequence
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.addReceivedSequence = function(sequence) {
|
||||
this._sequenceCache[sequence] = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Store received (validated) ID transaction
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.addReceivedId = function(id, transaction) {
|
||||
this._idCache[id] = transaction;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get received (validated) transaction by ID
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.getReceived = function(id) {
|
||||
return this._idCache[id];
|
||||
this._sequenceCache.set(String(sequence), true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check that sequence number has been consumed by a validated
|
||||
* transaction
|
||||
*
|
||||
* @param {Number} sequence
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.hasSequence = function(sequence) {
|
||||
return this._sequenceCache[sequence] || false;
|
||||
return this._sequenceCache.has(String(sequence));
|
||||
};
|
||||
|
||||
/**
|
||||
* Store received (validated) ID transaction
|
||||
*
|
||||
* @param {String} transaction id
|
||||
* @param {Transaction} transaction
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.addReceivedId = function(id, transaction) {
|
||||
this._idCache.set(id, transaction);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get received (validated) transaction by ID
|
||||
*
|
||||
* @param {String} transaction id
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.getReceived = function(id) {
|
||||
return this._idCache.get(id);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a submitted transaction by ID. Transactions
|
||||
* may have multiple associated IDs.
|
||||
*
|
||||
* @param {String} transaction id
|
||||
* @return {Transaction}
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.getSubmission = function(id, callback) {
|
||||
var result = false;
|
||||
TransactionQueue.prototype.getSubmission = function(id) {
|
||||
return lodash.find(this._queue, function(tx) {
|
||||
return lodash.contains(tx.submittedIDs, id);
|
||||
});
|
||||
};
|
||||
|
||||
for (var i=0, tx; tx=this._queue[i]; i++) {
|
||||
if (~tx.submittedIDs.indexOf(id)) {
|
||||
result = tx;
|
||||
break;
|
||||
/**
|
||||
* Get earliest ledger in the pending queue
|
||||
*
|
||||
* @return {Number} ledger
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.getMinLedger = function() {
|
||||
if (this.length() < 1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
var result = Infinity;
|
||||
|
||||
for (var i = 0; i < this.length(); i++) {
|
||||
if (this._queue[i].initialSubmitIndex < result) {
|
||||
result = this._queue[i].initialSubmitIndex;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isFinite(result)) {
|
||||
result = -1;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove a transaction from the queue
|
||||
*
|
||||
* @param {String|Transaction} transaction or id
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this._queue.length) {
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
this.save();
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a transaction to pending queue
|
||||
*
|
||||
* @param {Transaction} transaction
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.push = function(tx) {
|
||||
this._queue.push(tx);
|
||||
this.save();
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterate over pending transactions
|
||||
*
|
||||
* @param {Function} iterator
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.forEach = function(fn) {
|
||||
this._queue.forEach(fn);
|
||||
};
|
||||
|
||||
TransactionQueue.prototype.length = function() {
|
||||
/**
|
||||
* @return {Number} length of pending queue
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.length =
|
||||
TransactionQueue.prototype.getLength = function() {
|
||||
return this._queue.length;
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {Array} pending queue
|
||||
*/
|
||||
|
||||
TransactionQueue.prototype.getQueue = function() {
|
||||
return this._queue;
|
||||
};
|
||||
|
||||
exports.TransactionQueue = TransactionQueue;
|
||||
|
||||
@@ -2,29 +2,24 @@ var utils = require('./utils');
|
||||
var sjcl = utils.sjcl;
|
||||
var config = require('./config');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
var Base = require('./base').Base;
|
||||
|
||||
//
|
||||
// Abstract UInt class
|
||||
//
|
||||
// Base class for UInt??? classes
|
||||
// Base class for UInt classes
|
||||
//
|
||||
|
||||
var UInt = function () {
|
||||
// Internal form: NaN or BigInteger
|
||||
var UInt = function() {
|
||||
// Internal form: NaN or sjcl.bn
|
||||
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 {
|
||||
@@ -33,7 +28,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 {
|
||||
@@ -42,7 +37,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 {
|
||||
@@ -51,7 +46,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 {
|
||||
@@ -60,7 +55,7 @@ UInt.from_bits = function (j) {
|
||||
};
|
||||
|
||||
// Return a new UInt from j.
|
||||
UInt.from_bytes = function (j) {
|
||||
UInt.from_bytes = function(j) {
|
||||
if (j instanceof this) {
|
||||
return j.clone();
|
||||
} else {
|
||||
@@ -69,7 +64,7 @@ UInt.from_bytes = function (j) {
|
||||
};
|
||||
|
||||
// Return a new UInt from j.
|
||||
UInt.from_bn = function (j) {
|
||||
UInt.from_bn = function(j) {
|
||||
if (j instanceof this) {
|
||||
return j.clone();
|
||||
} else {
|
||||
@@ -78,7 +73,7 @@ UInt.from_bn = function (j) {
|
||||
};
|
||||
|
||||
// Return a new UInt from j.
|
||||
UInt.from_number = function (j) {
|
||||
UInt.from_number = function(j) {
|
||||
if (j instanceof this) {
|
||||
return j.clone();
|
||||
} else {
|
||||
@@ -86,33 +81,39 @@ UInt.from_number = function (j) {
|
||||
}
|
||||
};
|
||||
|
||||
UInt.is_valid = function (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 ("function" === typeof d._update) d._update();
|
||||
if (this._version_byte !== void(0)) {
|
||||
d._version_byte = this._version_byte;
|
||||
}
|
||||
|
||||
if (typeof d._update === 'function') {
|
||||
d._update();
|
||||
}
|
||||
|
||||
return d;
|
||||
};
|
||||
|
||||
UInt.prototype.equals = function (d) {
|
||||
return this._value instanceof BigInteger && d._value instanceof BigInteger && this._value.equals(d._value);
|
||||
UInt.prototype.equals = function(d) {
|
||||
return this.is_valid() && d.is_valid() && this._value.equals(d._value);
|
||||
};
|
||||
|
||||
UInt.prototype.is_valid = function () {
|
||||
return this._value instanceof BigInteger;
|
||||
UInt.prototype.is_valid = function() {
|
||||
return this._value instanceof sjcl.bn;
|
||||
};
|
||||
|
||||
UInt.prototype.is_zero = function () {
|
||||
return this._value.equals(BigInteger.ZERO);
|
||||
UInt.prototype.is_zero = function() {
|
||||
return this.is_valid() && this._value.equals(new sjcl.bn(0));
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -125,47 +126,45 @@ UInt.prototype.is_zero = function () {
|
||||
* 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 () {
|
||||
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 = BigInteger.valueOf();
|
||||
break;
|
||||
case undefined:
|
||||
case '0':
|
||||
case this.constructor.STR_ZERO:
|
||||
case this.constructor.ACCOUNT_ZERO:
|
||||
case this.constructor.HEX_ZERO:
|
||||
this._value = new sjcl.bn(0);
|
||||
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 sjcl.bn(1);
|
||||
break;
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
if ('string' !== typeof j) {
|
||||
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;
|
||||
}
|
||||
default:
|
||||
if (typeof j !== 'string') {
|
||||
this._value = NaN;
|
||||
} else if (this.constructor.width === j.length) {
|
||||
var hex = utils.arrayToHex(utils.stringToArray(j));
|
||||
this._value = new sjcl.bn(hex, 16);
|
||||
} else if ((this.constructor.width * 2) === j.length) {
|
||||
// XXX Check char set!
|
||||
this._value = new sjcl.bn(j, 16);
|
||||
} else {
|
||||
this._value = NaN;
|
||||
}
|
||||
}
|
||||
|
||||
this._update();
|
||||
@@ -173,12 +172,11 @@ UInt.prototype.parse_generic = function (j) {
|
||||
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 sjcl.bn(j, 16);
|
||||
} else {
|
||||
this._value = NaN;
|
||||
this._value = NaN;
|
||||
}
|
||||
|
||||
this._update();
|
||||
@@ -186,12 +184,13 @@ UInt.prototype.parse_hex = function (j) {
|
||||
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.parse_bytes(bytes);
|
||||
this._value = sjcl.bn.fromBits(j);
|
||||
// var bytes = sjcl.codec.bytes.fromBits(j);
|
||||
// this.parse_bytes(bytes);
|
||||
}
|
||||
|
||||
this._update();
|
||||
@@ -200,11 +199,12 @@ UInt.prototype.parse_bits = function (j) {
|
||||
};
|
||||
|
||||
|
||||
UInt.prototype.parse_bytes = function (j) {
|
||||
UInt.prototype.parse_bytes = function(j) {
|
||||
if (!Array.isArray(j) || j.length !== this.constructor.width) {
|
||||
this._value = NaN;
|
||||
this._value = NaN;
|
||||
} else {
|
||||
this._value = new BigInteger([0].concat(j), 256);
|
||||
var bits = sjcl.codec.bytes.toBits(j);
|
||||
this._value = sjcl.bn.fromBits(bits);
|
||||
}
|
||||
|
||||
this._update();
|
||||
@@ -215,11 +215,11 @@ UInt.prototype.parse_bytes = function (j) {
|
||||
|
||||
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) {
|
||||
var bytes = sjcl.codec.bytes.fromBits(j.toBits());
|
||||
this._value = new BigInteger(bytes, 256);
|
||||
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 sjcl.bn(utils.arrayToHex(bytes), 16);
|
||||
this._value = new sjcl.bn(j);
|
||||
} else {
|
||||
this._value = NaN;
|
||||
}
|
||||
@@ -229,14 +229,11 @@ UInt.prototype.parse_bn = function (j) {
|
||||
return this;
|
||||
};
|
||||
|
||||
UInt.prototype.parse_number = function (j) {
|
||||
UInt.prototype.parse_number = function(j) {
|
||||
this._value = NaN;
|
||||
|
||||
if ("number" === typeof j &&
|
||||
j === +j &&
|
||||
j > 0) {
|
||||
// XXX Better, faster way to get BigInteger from JS int?
|
||||
this._value = new BigInteger(""+j);
|
||||
if (typeof j === 'number' && isFinite(j) && j >= 0) {
|
||||
this._value = new sjcl.bn(j);
|
||||
}
|
||||
|
||||
this._update();
|
||||
@@ -245,43 +242,34 @@ UInt.prototype.parse_number = function (j) {
|
||||
};
|
||||
|
||||
// Convert from internal form.
|
||||
UInt.prototype.to_bytes = function () {
|
||||
if (!(this._value instanceof BigInteger))
|
||||
UInt.prototype.to_bytes = function() {
|
||||
if (!this.is_valid()) {
|
||||
return null;
|
||||
|
||||
var bytes = this._value.toByteArray();
|
||||
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);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
return sjcl.codec.bytes.fromBits(this.to_bits());
|
||||
};
|
||||
|
||||
UInt.prototype.to_hex = function () {
|
||||
if (!(this._value instanceof BigInteger))
|
||||
UInt.prototype.to_hex = function() {
|
||||
if (!this.is_valid()) {
|
||||
return null;
|
||||
|
||||
var bytes = this.to_bytes();
|
||||
return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(bytes)).toUpperCase();
|
||||
}
|
||||
return sjcl.codec.hex.fromBits(this.to_bits()).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.is_valid()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var bytes = this.to_bytes();
|
||||
|
||||
return sjcl.codec.bytes.toBits(bytes);
|
||||
return this._value.toBits(this.constructor.width * 8);
|
||||
};
|
||||
|
||||
UInt.prototype.to_bn = function () {
|
||||
if (!(this._value instanceof BigInteger))
|
||||
UInt.prototype.to_bn = function() {
|
||||
if (!this.is_valid()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var bits = this.to_bits();
|
||||
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var config = require('./config');
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
var UInt = require('./uint').UInt,
|
||||
Base = require('./base').Base;
|
||||
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);
|
||||
|
||||
@@ -21,9 +14,9 @@ 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);
|
||||
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;
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var config = require('./config');
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
var UInt = require('./uint').UInt;
|
||||
var Base = require('./base').Base;
|
||||
|
||||
@@ -12,11 +9,9 @@ var Base = require('./base').Base;
|
||||
// UInt160 support
|
||||
//
|
||||
|
||||
var UInt160 = extend(function () {
|
||||
// Internal form: NaN or BigInteger
|
||||
var UInt160 = extend(function() {
|
||||
this._value = NaN;
|
||||
this._version_byte = void(0);
|
||||
|
||||
this._update();
|
||||
}, UInt);
|
||||
|
||||
@@ -31,20 +26,19 @@ var HEX_ONE = UInt160.HEX_ONE = '0000000000000000000000000000000000000
|
||||
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) {
|
||||
UInt160.prototype.set_version = function(j) {
|
||||
this._version_byte = j;
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
UInt160.prototype.get_version = function () {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -52,7 +46,7 @@ UInt160.prototype.parse_json = function (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.parse_number(j);
|
||||
this._version_byte = Base.VER_ACCOUNT_ID;
|
||||
} else if (typeof j !== 'string') {
|
||||
this._value = NaN;
|
||||
@@ -68,11 +62,11 @@ UInt160.prototype.parse_json = function (j) {
|
||||
return this;
|
||||
};
|
||||
|
||||
UInt160.prototype.parse_generic = function (j) {
|
||||
UInt160.prototype.parse_generic = function(j) {
|
||||
UInt.prototype.parse_generic.call(this, j);
|
||||
|
||||
if (isNaN(this._value)) {
|
||||
if ("string" === typeof j && j[0] === 'r') {
|
||||
if ((typeof j === 'string') && j[0] === 'r') {
|
||||
this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);
|
||||
}
|
||||
}
|
||||
@@ -83,13 +77,14 @@ UInt160.prototype.parse_generic = function (j) {
|
||||
};
|
||||
|
||||
// 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) {
|
||||
if (this.is_valid()) {
|
||||
// If this value has a type, return a Base58 encoded string.
|
||||
if ("number" === typeof this._version_byte) {
|
||||
if (typeof this._version_byte === 'number') {
|
||||
var output = Base.encode_check(this._version_byte, this.to_bytes());
|
||||
|
||||
if (opts.gateways && output in opts.gateways) {
|
||||
output = opts.gateways[output];
|
||||
}
|
||||
|
||||
@@ -1,31 +1,22 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var config = require('./config');
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
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 () {
|
||||
// Internal form: NaN or BigInteger
|
||||
this._value = NaN;
|
||||
var UInt256 = extend(function() {
|
||||
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;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
Function.prototype.method = function(name, func) {
|
||||
this.prototype[name] = func;
|
||||
return this;
|
||||
};
|
||||
|
||||
function getMantissaDecimalString(bignum) {
|
||||
var mantissa = bignum.toPrecision(16)
|
||||
.replace(/\./, '') // remove decimal point
|
||||
.replace(/e.*/, '') // remove scientific notation
|
||||
.replace(/^0*/, ''); // remove leading zeroes
|
||||
while (mantissa.length < 16) {
|
||||
mantissa += '0'; // add trailing zeroes until length is 16
|
||||
}
|
||||
return mantissa;
|
||||
}
|
||||
|
||||
function filterErr(code, done) {
|
||||
return function(e) {
|
||||
@@ -20,7 +27,7 @@ function throwErr(done) {
|
||||
|
||||
function trace(comment, func) {
|
||||
return function() {
|
||||
console.log("%s: %s", trace, arguments.toString);
|
||||
console.log('%s: %s', trace, arguments.toString);
|
||||
func(arguments);
|
||||
};
|
||||
};
|
||||
@@ -74,6 +81,13 @@ function hexToArray(h) {
|
||||
return stringToArray(hexToString(h));
|
||||
};
|
||||
|
||||
function arrayToHex(a) {
|
||||
return a.map(function(byteValue) {
|
||||
var hex = byteValue.toString(16);
|
||||
return hex.length > 1 ? hex : '0' + hex;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function chunkString(str, n, leftAlign) {
|
||||
var ret = [];
|
||||
var i=0, len=str.length;
|
||||
@@ -94,7 +108,7 @@ function chunkString(str, n, leftAlign) {
|
||||
|
||||
function assert(assertion, msg) {
|
||||
if (!assertion) {
|
||||
throw new Error("Assertion failed" + (msg ? ": "+msg : "."));
|
||||
throw new Error('Assertion failed' + (msg ? ': ' + msg : '.'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -135,7 +149,12 @@ function fromTimestamp(rpepoch) {
|
||||
rpepoch = rpepoch.getTime();
|
||||
}
|
||||
|
||||
return Math.round(rpepoch/1000) - 0x386D4380;
|
||||
return Math.round(rpepoch / 1000) - 0x386D4380;
|
||||
};
|
||||
|
||||
exports.time = {
|
||||
fromRipple: toTimestamp,
|
||||
toRipple: fromTimestamp
|
||||
};
|
||||
|
||||
exports.trace = trace;
|
||||
@@ -144,15 +163,16 @@ exports.hexToString = hexToString;
|
||||
exports.hexToArray = hexToArray;
|
||||
exports.stringToArray = stringToArray;
|
||||
exports.stringToHex = stringToHex;
|
||||
exports.arrayToHex = arrayToHex;
|
||||
exports.chunkString = chunkString;
|
||||
exports.assert = assert;
|
||||
exports.arrayUnique = arrayUnique;
|
||||
exports.toTimestamp = toTimestamp;
|
||||
exports.fromTimestamp = fromTimestamp;
|
||||
exports.getMantissaDecimalString = getMantissaDecimalString;
|
||||
|
||||
// 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
|
||||
|
||||
8
src/js/ripple/wallet.js
Normal file
8
src/js/ripple/wallet.js
Normal file
@@ -0,0 +1,8 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
|
||||
var WalletGenerator = require('ripple-wallet-generator')({
|
||||
sjcl: sjcl
|
||||
});
|
||||
|
||||
module.exports = WalletGenerator;
|
||||
|
||||
83
src/js/sjcl-custom/sjcl-ecc-pointextras.js
Normal file
83
src/js/sjcl-custom/sjcl-ecc-pointextras.js
Normal 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() +
|
||||
')';
|
||||
};
|
||||
17
src/js/sjcl-custom/sjcl-ecdsa-canonical.js
Normal file
17
src/js/sjcl-custom/sjcl-ecdsa-canonical.js
Normal 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));
|
||||
};
|
||||
|
||||
306
src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js
Normal file
306
src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js
Normal 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['k256']] 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['k256'];
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
};
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
// ----- for secp256k1 ------
|
||||
|
||||
// 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",
|
||||
0,
|
||||
7,
|
||||
"0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
||||
"0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
|
||||
);
|
||||
sjcl.ecc.point.prototype.toBytesCompressed = function () {
|
||||
var header = this.y.mod(2).toString() == "0x0" ? 0x02 : 0x03;
|
||||
return [header].concat(sjcl.codec.bytes.fromBits(this.x.toBits()))
|
||||
};
|
||||
|
||||
// Replace point addition and doubling algorithms
|
||||
// NIST-P256 is a=-3, we need algorithms for a=0
|
||||
//
|
||||
// This is a custom point addition formula that
|
||||
// only works for a=-3 Jacobian curve. It's much
|
||||
// faster than the generic implementation
|
||||
sjcl.ecc.pointJac.prototype.add = function(T) {
|
||||
var S = this;
|
||||
if (S.curve !== T.curve) {
|
||||
@@ -43,7 +42,7 @@ sjcl.ecc.pointJac.prototype.add = function(T) {
|
||||
var j = h.mul(i);
|
||||
var r = s2.sub(S.y).doubleM();
|
||||
var v = S.x.mul(i);
|
||||
|
||||
|
||||
var x = r.square().subM(j).subM(v.copy().doubleM());
|
||||
var y = r.mul(v.sub(x)).subM(S.y.mul(j).doubleM());
|
||||
var z = S.z.add(h).square().subM(z1z1).subM(hh);
|
||||
@@ -51,6 +50,9 @@ sjcl.ecc.pointJac.prototype.add = function(T) {
|
||||
return new sjcl.ecc.pointJac(this.curve,x,y,z);
|
||||
};
|
||||
|
||||
// This is a custom doubling algorithm that
|
||||
// only works for a=-3 Jacobian curve. It's much
|
||||
// faster than the generic implementation
|
||||
sjcl.ecc.pointJac.prototype.doubl = function () {
|
||||
if (this.isIdentity) { return this; }
|
||||
|
||||
@@ -62,11 +64,13 @@ 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);
|
||||
};
|
||||
|
||||
sjcl.ecc.point.prototype.toBytesCompressed = function () {
|
||||
var header = this.y.mod(2).toString() == "0x0" ? 0x02 : 0x03;
|
||||
return [header].concat(sjcl.codec.bytes.fromBits(this.x.toBits()))
|
||||
};
|
||||
// DEPRECATED:
|
||||
// previously the c256 curve was overridden with the secp256k1 curve
|
||||
// since then, sjcl has been updated to support k256
|
||||
// this override exist to keep supporting the old c256 with k256 behavior
|
||||
// this will be removed in future release
|
||||
sjcl.ecc.curves.c256 = sjcl.ecc.curves.k256;
|
||||
@@ -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.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;
|
||||
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;
|
||||
};
|
||||
|
||||
2
src/js/sjcl/.gitignore
vendored
Normal file
2
src/js/sjcl/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
core.js
|
||||
core_closure.js
|
||||
9
src/js/sjcl/.travis.yml
Normal file
9
src/js/sjcl/.travis.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
before_script: ./configure --with-all
|
||||
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.11"
|
||||
- "0.10"
|
||||
- "0.8"
|
||||
# 0.6 appears to be unreliable on Travis at the moment.
|
||||
# - "0.6"
|
||||
@@ -54,10 +54,11 @@ lint: core.js core/*.js test/*.js browserTest/*.js lint/coding_guidelines.pl
|
||||
lint/coding_guidelines.pl core/*.js test/*.js browserTest/*.js
|
||||
|
||||
|
||||
TEST_COMMON= browserTest/rhinoUtil.js test/test.js
|
||||
TEST_COMMON= browserTest/nodeUtil.js test/test.js
|
||||
|
||||
TEST_SCRIPTS= $(TEST_COMMON) \
|
||||
test/aes_vectors.js test/aes_test.js \
|
||||
test/bitArray_vectors.js test/bitArray_test.js \
|
||||
test/ocb2_vectors.js test/ocb2_test.js \
|
||||
test/ccm_vectors.js test/ccm_test.js \
|
||||
test/cbc_vectors.js test/cbc_test.js \
|
||||
@@ -70,18 +71,14 @@ TEST_SCRIPTS= $(TEST_COMMON) \
|
||||
test/hmac_vectors.js test/hmac_test.js \
|
||||
test/pbkdf2_test.js \
|
||||
test/bn_vectors.js test/bn_test.js \
|
||||
test/ecdsa_test.js test/ecdsa_vectors.js test/ecdh_test.js
|
||||
test/ecdsa_test.js test/ecdsa_vectors.js test/ecdh_test.js \
|
||||
test/srp_vectors.js test/srp_test.js \
|
||||
test/json_test.js
|
||||
|
||||
TEST_SCRIPTS_OPT= $(TEST_COMMON) \
|
||||
test/srp_vectors.js test/srp_test.js
|
||||
# Run all tests in node.js.
|
||||
|
||||
# Rhino fails at -O 0. Probably because the big files full of test vectors blow the
|
||||
# bytecode limit. So, run most tests with -O -1. But modular exponentiation is
|
||||
# currently very slow (on Rhino), so run the SRP test with optimizations on.
|
||||
|
||||
test: sjcl.js $(TEST_SCRIPTS) test/run_tests_rhino.js
|
||||
@rhino -O -1 -w test/run_tests_rhino.js $< $(TEST_SCRIPTS)
|
||||
@rhino -O 9 -w test/run_tests_rhino.js $< $(TEST_SCRIPTS_OPT)
|
||||
test: sjcl.js $(TEST_SCRIPTS) test/run_tests_node.js
|
||||
node test/run_tests_node.js $< $(TEST_SCRIPTS)
|
||||
|
||||
tidy:
|
||||
find . -name '*~' -delete
|
||||
|
||||
21
src/js/sjcl/README.md
Normal file
21
src/js/sjcl/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
sjcl
|
||||
====
|
||||
|
||||
[](https://travis-ci.org/bitwiseshiftleft/sjcl)
|
||||
|
||||
Stanford Javascript Crypto Library
|
||||
|
||||
Security Advisories
|
||||
===
|
||||
* 12.02.2014: the current development version has a paranoia bug in the ecc module. The bug was introduced in commit [ac0b3fe0](https://github.com/bitwiseshiftleft/sjcl/commit/ac0b3fe0) and might affect ecc key generation on platforms without a platform random number generator.
|
||||
*
|
||||
|
||||
Security Contact
|
||||
====
|
||||
Security Mail: sjcl@ovt.me
|
||||
OpenPGP-Key Fingerprint: 0D54 3E52 87B4 EC06 3FA9 0115 72ED A6C7 7AAF 48ED
|
||||
Keyserver: pool.sks-keyservers.net
|
||||
|
||||
Documentation
|
||||
====
|
||||
The documentation is available [here](http://bitwiseshiftleft.github.io/sjcl/doc/)
|
||||
12
src/js/sjcl/bower.json
Normal file
12
src/js/sjcl/bower.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "sjcl",
|
||||
"version": "1.0.0",
|
||||
"main": ["./sjcl.js"],
|
||||
"ignore": [
|
||||
"**/*",
|
||||
"!README.md",
|
||||
"!README/*",
|
||||
"!bower.json",
|
||||
"!sjcl.js"
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
browserUtil = {};
|
||||
|
||||
browserUtil.isRhino = (typeof(window) === 'undefined');
|
||||
browserUtil.isNodeJS = (typeof(window) === 'undefined');
|
||||
|
||||
/**
|
||||
* Pause (for the graphics to update and the script timer to clear), then run the
|
||||
|
||||
88
src/js/sjcl/browserTest/entropy.html
Normal file
88
src/js/sjcl/browserTest/entropy.html
Normal file
@@ -0,0 +1,88 @@
|
||||
<html>
|
||||
<head>
|
||||
|
||||
<title>Entropy Generator Progress</title>
|
||||
<!-- ProgressBar source: http://stackoverflow.com/questions/7190898/progress-bar-with-html-and-css -->
|
||||
|
||||
<style>
|
||||
#progressbar {
|
||||
background-color: black;
|
||||
border-radius: 13px; /* (height of inner div) / 2 + padding */
|
||||
padding: 3px;
|
||||
}
|
||||
#progressbar > div {
|
||||
background-color: orange;
|
||||
width: 0%; /* Adjust with JavaScript */
|
||||
height: 20px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script type="text/javascript" src="../sjcl.js">
|
||||
</script>
|
||||
|
||||
<script type="text/javascript">
|
||||
|
||||
var busy = 0;
|
||||
var collecting = 0;
|
||||
|
||||
function showprogress () {
|
||||
var barwidth = document.getElementById ("progresswidth");
|
||||
var paranoia = parseInt (document.getElementById ("paranoialevel").value);
|
||||
var progress = 100 * sjcl.random.getProgress (paranoia);
|
||||
barwidth.style.width = progress+"%";
|
||||
if (!sjcl.random.isReady (paranoia)) {
|
||||
setTimeout ("showprogress()", 10, "JavaScript");
|
||||
} else {
|
||||
busy = 0;
|
||||
document.getElementById ("startbutton").style.disabled = 1;
|
||||
}
|
||||
}
|
||||
|
||||
function startup () {
|
||||
if (collecting == 0) {
|
||||
sjcl.random.startCollectors ();
|
||||
collecting = 1;
|
||||
}
|
||||
if (busy == 0) {
|
||||
busy = 1;
|
||||
document.getElementById ("startbutton").style.disabled = 1;
|
||||
showprogress ();
|
||||
}
|
||||
}
|
||||
|
||||
function consume (numbits) {
|
||||
var collector = document.getElementById ("collector");
|
||||
collector.value = "retrieving random data";
|
||||
var paranoia = document.getElementById ("paranoialevel").value;
|
||||
var numwords = Math.ceil (numbits / 32);
|
||||
var bits = sjcl.random.randomWords (numwords, paranoia);
|
||||
collector.value = '';
|
||||
for (var i=0; i<numwords; i++) {
|
||||
var hi = (bits [i] >> 16) & 0x0000ffff;
|
||||
var lo = bits [i] & 0x0000ffff;
|
||||
collector.value = collector.value + hi.toString (16) + lo.toString (16);
|
||||
}
|
||||
startup ();
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<h1>Entropy Generator Progress</h1>
|
||||
|
||||
<p>Target: 192 bits, available at paranoia level 5.</p>
|
||||
|
||||
<p>Corresponding paranoia level from [0,1..10]: <input type="text" value="5" id="paranoialevel"/> <input type=button onclick="startup ()" id="startbutton" value=" Start >> "> (the idea being that you can see the progress bar advance gently from empty/black to full/yellow after you press this)</p>
|
||||
|
||||
<p><input type=button onclick="consume (192)" value=" Consume 192 bits >> "><input type=text id=collector size=50 value="" onkeypress="consume (192)"> (also consumes 192 bits with every keypress in the text field; use key repeat to consume swiftly)</p>
|
||||
|
||||
<div id="progressbar">
|
||||
<div id="progresswidth"></div>
|
||||
</div>
|
||||
|
||||
<p>Please move your mouse, play around and generally introduce entropy into your environment.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
44
src/js/sjcl/browserTest/nodeUtil.js
Normal file
44
src/js/sjcl/browserTest/nodeUtil.js
Normal file
@@ -0,0 +1,44 @@
|
||||
browserUtil = {
|
||||
isNodeJS: true,
|
||||
|
||||
pauseAndThen: function (cb) { cb(); },
|
||||
|
||||
cpsIterate: function (f, start, end, pause, callback) {
|
||||
function go() {
|
||||
var called = false;
|
||||
if (start >= end) {
|
||||
callback && callback();
|
||||
} else {
|
||||
f(start, function () {
|
||||
if (!called) { called = true; start++; go(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
go (start);
|
||||
},
|
||||
|
||||
cpsMap: function (map, list, pause, callback) {
|
||||
browserUtil.cpsIterate(function (i, cb) { map(list[i], i, list.length, cb); },
|
||||
0, list.length, pause, callback);
|
||||
},
|
||||
|
||||
loadScripts: function(scriptNames, callback) {
|
||||
for (i=0; i<scriptNames.length; i++) {
|
||||
load(scriptNames[i]);
|
||||
callback && callback();
|
||||
}
|
||||
},
|
||||
|
||||
write: function(type, message) {
|
||||
console.log(message);
|
||||
return { update: function (type2, message2) {
|
||||
if (type2 === 'pass') { console.log(" + " + message2); }
|
||||
else if (type2 === 'unimplemented') { console.log(" ? " + message2); }
|
||||
else { console.log(" - " + message2); }
|
||||
}};
|
||||
},
|
||||
|
||||
writeNewline: function () { console.log(""); },
|
||||
|
||||
status: function(message) {}
|
||||
};
|
||||
@@ -16,7 +16,7 @@ sub digitize {
|
||||
}
|
||||
|
||||
while (<>) {
|
||||
s/([^a-zA-Z0-9_])(\d+)/$1 . digitize $2/eg;
|
||||
s/([^a-zA-Z0-9_"])(\d+)/$1 . digitize $2/eg;
|
||||
print;
|
||||
}
|
||||
|
||||
|
||||
11
src/js/sjcl/configure
vendored
11
src/js/sjcl/configure
vendored
@@ -4,12 +4,13 @@ use strict;
|
||||
|
||||
my ($arg, $i, $j, $targ);
|
||||
|
||||
my @targets = qw/sjcl aes bitArray codecString codecHex codecBase64 codecBytes sha256 sha512 sha1 ccm cbc ocb2 gcm hmac pbkdf2 random convenience bn ecc srp/;
|
||||
my @targets = qw/sjcl aes bitArray codecString codecHex codecBase32 codecBase64 codecBytes sha256 sha512 sha1 ccm cbc ocb2 gcm hmac pbkdf2 random convenience bn ecc srp/;
|
||||
my %deps = ('aes'=>'sjcl',
|
||||
'bitArray'=>'sjcl',
|
||||
'codecString'=>'bitArray',
|
||||
'codecHex'=>'bitArray',
|
||||
'codecBase64'=>'bitArray',
|
||||
'codecBase32'=>'bitArray',
|
||||
'codecBytes'=>'bitArray',
|
||||
'sha256'=>'codecString',
|
||||
'sha512'=>'codecString',
|
||||
@@ -32,10 +33,10 @@ my %enabled = ();
|
||||
$enabled{$_} = 0 foreach (@targets);
|
||||
|
||||
# by default, all but codecBytes, srp, bn
|
||||
$enabled{$_} = 1 foreach (qw/aes bitArray codecString codecHex codecBase64 sha256 ccm ocb2 gcm hmac pbkdf2 random convenience/);
|
||||
$enabled{$_} = 1 foreach (qw/aes bitArray codecString codecHex codecBase32 codecBase64 sha256 ccm ocb2 gcm hmac pbkdf2 random convenience/);
|
||||
|
||||
# argument parsing
|
||||
while ($arg = shift @ARGV) {
|
||||
while (my $arg = shift @ARGV) {
|
||||
if ($arg =~ /^--?with-all$/) {
|
||||
foreach (@targets) {
|
||||
if ($enabled{$_} == 0) {
|
||||
@@ -97,7 +98,7 @@ my $config = '';
|
||||
my $pconfig;
|
||||
|
||||
# dependency analysis: forbidden
|
||||
foreach $i (@targets) {
|
||||
foreach my $i (@targets) {
|
||||
if ($enabled{$i} > 0) {
|
||||
foreach $j (split /,/, $deps{$i}) {
|
||||
if ($enabled{$j} == -1) {
|
||||
@@ -114,7 +115,7 @@ foreach $i (@targets) {
|
||||
}
|
||||
|
||||
# reverse
|
||||
foreach $i (reverse @targets) {
|
||||
foreach my $i (reverse @targets) {
|
||||
if ($enabled{$i} > 0) {
|
||||
foreach $j (split /,/, $deps{$i}) {
|
||||
if ($enabled{$j} < $enabled{$i}) {
|
||||
|
||||
@@ -74,7 +74,7 @@ sjcl.bitArray = {
|
||||
return a1.concat(a2);
|
||||
}
|
||||
|
||||
var out, i, last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);
|
||||
var last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);
|
||||
if (shift === 32) {
|
||||
return a1.concat(a2);
|
||||
} else {
|
||||
@@ -183,5 +183,19 @@ sjcl.bitArray = {
|
||||
*/
|
||||
_xor4: function(x,y) {
|
||||
return [x[0]^y[0],x[1]^y[1],x[2]^y[2],x[3]^y[3]];
|
||||
},
|
||||
|
||||
/** byteswap a word array inplace.
|
||||
* (does not handle partial words)
|
||||
* @param {sjcl.bitArray} a word array
|
||||
* @return {sjcl.bitArray} byteswapped array
|
||||
*/
|
||||
byteswapM: function(a) {
|
||||
var i, v, m = 0xff00;
|
||||
for (i = 0; i < a.length; ++i) {
|
||||
v = a[i];
|
||||
a[i] = (v >>> 24) | ((v >>> 8) & m) | ((v & m) << 8) | (v << 24);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ sjcl.bn.prototype = {
|
||||
* Initializes this with it, either as a bn, a number, or a hex string.
|
||||
*/
|
||||
initWith: function(it) {
|
||||
var i=0, k, n, l;
|
||||
var i=0, k;
|
||||
switch(typeof it) {
|
||||
case "object":
|
||||
this.limbs = it.limbs.slice(0);
|
||||
@@ -328,7 +328,7 @@ sjcl.bn.prototype = {
|
||||
carry = (l-m)*ipv;
|
||||
}
|
||||
if (carry === -1) {
|
||||
limbs[i-1] -= this.placeVal;
|
||||
limbs[i-1] -= pv;
|
||||
}
|
||||
return this;
|
||||
},
|
||||
@@ -370,7 +370,9 @@ sjcl.bn.prototype = {
|
||||
}
|
||||
};
|
||||
|
||||
/** @this { sjcl.bn } */
|
||||
/** @memberOf sjcl.bn
|
||||
* @this { sjcl.bn }
|
||||
*/
|
||||
sjcl.bn.fromBits = function(bits) {
|
||||
var Class = this, out = new Class(), words=[], w=sjcl.bitArray, t = this.prototype,
|
||||
l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix;
|
||||
@@ -394,7 +396,9 @@ sjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;
|
||||
* i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.
|
||||
*/
|
||||
sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
/** @constructor */
|
||||
/** @constructor
|
||||
* @private
|
||||
*/
|
||||
function p(it) {
|
||||
this.initWith(it);
|
||||
/*if (this.limbs[this.modOffset]) {
|
||||
@@ -427,10 +431,11 @@ sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
ppr.modulus.cnormalize();
|
||||
|
||||
/** Approximate reduction mod p. May leave a number which is negative or slightly larger than p.
|
||||
* @this {sjcl.bn}
|
||||
* @memberof sjcl.bn
|
||||
* @this { sjcl.bn }
|
||||
*/
|
||||
ppr.reduce = function() {
|
||||
var i, k, l, mo = this.modOffset, limbs = this.limbs, aff, off = this.offset, ol = this.offset.length, fac = this.factor, ll;
|
||||
var i, k, l, mo = this.modOffset, limbs = this.limbs, off = this.offset, ol = this.offset.length, fac = this.factor, ll;
|
||||
|
||||
i = this.minOffset;
|
||||
while (limbs.length > mo) {
|
||||
@@ -452,7 +457,9 @@ sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
return this;
|
||||
};
|
||||
|
||||
/** @this {sjcl.bn} */
|
||||
/** @memberof sjcl.bn
|
||||
* @this { sjcl.bn }
|
||||
*/
|
||||
ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function() {
|
||||
var limbs = this.limbs, i = limbs.length - 1, k, l;
|
||||
this.reduce();
|
||||
@@ -467,7 +474,8 @@ sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
};
|
||||
|
||||
/** mostly constant-time, very expensive full reduction.
|
||||
* @this {sjcl.bn}
|
||||
* @memberof sjcl.bn
|
||||
* @this { sjcl.bn }
|
||||
*/
|
||||
ppr.fullReduce = function() {
|
||||
var greater, i;
|
||||
@@ -501,7 +509,9 @@ sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
};
|
||||
|
||||
|
||||
/** @this {sjcl.bn} */
|
||||
/** @memberof sjcl.bn
|
||||
* @this { sjcl.bn }
|
||||
*/
|
||||
ppr.inverse = function() {
|
||||
return (this.power(this.modulus.sub(2)));
|
||||
};
|
||||
@@ -512,18 +522,24 @@ sjcl.bn.pseudoMersennePrime = function(exponent, coeff) {
|
||||
};
|
||||
|
||||
// a small Mersenne prime
|
||||
var sbp = sjcl.bn.pseudoMersennePrime;
|
||||
sjcl.bn.prime = {
|
||||
p127: sjcl.bn.pseudoMersennePrime(127, [[0,-1]]),
|
||||
p127: sbp(127, [[0,-1]]),
|
||||
|
||||
// Bernstein's prime for Curve25519
|
||||
p25519: sjcl.bn.pseudoMersennePrime(255, [[0,-19]]),
|
||||
p25519: sbp(255, [[0,-19]]),
|
||||
|
||||
// Koblitz primes
|
||||
p192k: sbp(192, [[32,-1],[12,-1],[8,-1],[7,-1],[6,-1],[3,-1],[0,-1]]),
|
||||
p224k: sbp(224, [[32,-1],[12,-1],[11,-1],[9,-1],[7,-1],[4,-1],[1,-1],[0,-1]]),
|
||||
p256k: sbp(256, [[32,-1],[9,-1],[8,-1],[7,-1],[6,-1],[4,-1],[0,-1]]),
|
||||
|
||||
// NIST primes
|
||||
p192: sjcl.bn.pseudoMersennePrime(192, [[0,-1],[64,-1]]),
|
||||
p224: sjcl.bn.pseudoMersennePrime(224, [[0,1],[96,-1]]),
|
||||
p256: sjcl.bn.pseudoMersennePrime(256, [[0,-1],[96,1],[192,1],[224,-1]]),
|
||||
p384: sjcl.bn.pseudoMersennePrime(384, [[0,-1],[32,1],[96,-1],[128,-1]]),
|
||||
p521: sjcl.bn.pseudoMersennePrime(521, [[0,-1]])
|
||||
p192: sbp(192, [[0,-1],[64,-1]]),
|
||||
p224: sbp(224, [[0,1],[96,-1]]),
|
||||
p256: sbp(256, [[0,-1],[96,1],[192,1],[224,-1]]),
|
||||
p384: sbp(384, [[0,-1],[32,1],[96,-1],[128,-1]]),
|
||||
p521: sbp(521, [[0,-1]])
|
||||
};
|
||||
|
||||
sjcl.bn.random = function(modulus, paranoia) {
|
||||
|
||||
@@ -5,18 +5,18 @@
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace
|
||||
* Dangerous: CBC mode with PKCS#5 padding.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
if (sjcl.beware === undefined) {
|
||||
sjcl.beware = {};
|
||||
}
|
||||
sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."
|
||||
] = function() {
|
||||
/** @namespace
|
||||
* Dangerous: CBC mode with PKCS#5 padding.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
sjcl.mode.cbc = {
|
||||
/** The name of the mode.
|
||||
* @constant
|
||||
@@ -100,7 +100,7 @@ sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity.
|
||||
|
||||
/* check and remove the pad */
|
||||
bi = output[i-1] & 255;
|
||||
if (bi == 0 || bi > 16) {
|
||||
if (bi === 0 || bi > 16) {
|
||||
throw new sjcl.exception.corrupt("pkcs#5 padding corrupt");
|
||||
}
|
||||
bo = bi * 0x1010101;
|
||||
|
||||
@@ -25,7 +25,7 @@ sjcl.mode.ccm = {
|
||||
* @return {bitArray} The encrypted data, an array of bytes.
|
||||
*/
|
||||
encrypt: function(prf, plaintext, iv, adata, tlen) {
|
||||
var L, i, out = plaintext.slice(0), tag, w=sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;
|
||||
var L, out = plaintext.slice(0), tag, w=sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;
|
||||
tlen = tlen || 64;
|
||||
adata = adata || [];
|
||||
|
||||
@@ -59,7 +59,7 @@ sjcl.mode.ccm = {
|
||||
decrypt: function(prf, ciphertext, iv, adata, tlen) {
|
||||
tlen = tlen || 64;
|
||||
adata = adata || [];
|
||||
var L, i,
|
||||
var L,
|
||||
w=sjcl.bitArray,
|
||||
ivl = w.bitLength(iv) / 8,
|
||||
ol = w.bitLength(ciphertext),
|
||||
@@ -101,7 +101,7 @@ sjcl.mode.ccm = {
|
||||
*/
|
||||
_computeTag: function(prf, plaintext, iv, adata, tlen, L) {
|
||||
// compute B[0]
|
||||
var q, mac, field = 0, offset = 24, tmp, i, macData = [], w=sjcl.bitArray, xor = w._xor4;
|
||||
var mac, tmp, i, macData = [], w=sjcl.bitArray, xor = w._xor4;
|
||||
|
||||
tlen /= 8;
|
||||
|
||||
@@ -161,7 +161,7 @@ sjcl.mode.ccm = {
|
||||
* @private
|
||||
*/
|
||||
_ctrMode: function(prf, data, iv, tag, tlen, L) {
|
||||
var enc, i, w=sjcl.bitArray, xor = w._xor4, ctr, b, l = data.length, bl=w.bitLength(data);
|
||||
var enc, i, w=sjcl.bitArray, xor = w._xor4, ctr, l = data.length, bl=w.bitLength(data);
|
||||
|
||||
// start the ctr
|
||||
ctr = w.concat([w.partial(8,L-1)],iv).concat([0,0,0]).slice(0,4);
|
||||
|
||||
64
src/js/sjcl/core/codecBase32.js
Normal file
64
src/js/sjcl/core/codecBase32.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/** @fileOverview Bit array codec implementations.
|
||||
*
|
||||
* @author Nils Kenneweg
|
||||
*/
|
||||
|
||||
/** @namespace Base32 encoding/decoding */
|
||||
sjcl.codec.base32 = {
|
||||
/** The base32 alphabet.
|
||||
* @private
|
||||
*/
|
||||
_chars: "0123456789abcdefghjkmnpqrstvwxyz",
|
||||
|
||||
/* bits in an array */
|
||||
BITS: 32,
|
||||
/* base to encode at (2^x) */
|
||||
BASE: 5,
|
||||
/* bits - base */
|
||||
REMAINING: 27,
|
||||
|
||||
/** Convert from a bitArray to a base32 string. */
|
||||
fromBits: function (arr, _noEquals) {
|
||||
var BITS = sjcl.codec.base32.BITS, BASE = sjcl.codec.base32.BASE, REMAINING = sjcl.codec.base32.REMAINING;
|
||||
var out = "", i, bits=0, c = sjcl.codec.base32._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
|
||||
|
||||
for (i=0; out.length * BASE <= bl; ) {
|
||||
out += c.charAt((ta ^ arr[i]>>>bits) >>> REMAINING);
|
||||
if (bits < BASE) {
|
||||
ta = arr[i] << (BASE-bits);
|
||||
bits += REMAINING;
|
||||
i++;
|
||||
} else {
|
||||
ta <<= BASE;
|
||||
bits -= BASE;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Convert from a base32 string to a bitArray */
|
||||
toBits: function(str) {
|
||||
var BITS = sjcl.codec.base32.BITS, BASE = sjcl.codec.base32.BASE, REMAINING = sjcl.codec.base32.REMAINING;
|
||||
var out = [], i, bits=0, c = sjcl.codec.base32._chars, ta=0, x;
|
||||
|
||||
for (i=0; i<str.length; i++) {
|
||||
x = c.indexOf(str.charAt(i));
|
||||
if (x < 0) {
|
||||
throw new sjcl.exception.invalid("this isn't base32!");
|
||||
}
|
||||
if (bits > REMAINING) {
|
||||
bits -= REMAINING;
|
||||
out.push(ta ^ x>>>bits);
|
||||
ta = x << (BITS-bits);
|
||||
} else {
|
||||
bits += BASE;
|
||||
ta ^= x << (BITS-bits);
|
||||
}
|
||||
}
|
||||
if (bits&56) {
|
||||
out.push(sjcl.bitArray.partial(bits&56, ta, 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
@@ -15,7 +15,9 @@ sjcl.codec.base64 = {
|
||||
/** Convert from a bitArray to a base64 string. */
|
||||
fromBits: function (arr, _noEquals, _url) {
|
||||
var out = "", i, bits=0, c = sjcl.codec.base64._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
|
||||
if (_url) c = c.substr(0,62) + '-_';
|
||||
if (_url) {
|
||||
c = c.substr(0,62) + '-_';
|
||||
}
|
||||
for (i=0; out.length * 6 < bl; ) {
|
||||
out += c.charAt((ta ^ arr[i]>>>bits) >>> 26);
|
||||
if (bits < 6) {
|
||||
@@ -35,7 +37,9 @@ sjcl.codec.base64 = {
|
||||
toBits: function(str, _url) {
|
||||
str = str.replace(/\s|=/g,'');
|
||||
var out = [], i, bits=0, c = sjcl.codec.base64._chars, ta=0, x;
|
||||
if (_url) c = c.substr(0,62) + '-_';
|
||||
if (_url) {
|
||||
c = c.substr(0,62) + '-_';
|
||||
}
|
||||
for (i=0; i<str.length; i++) {
|
||||
x = c.indexOf(str.charAt(i));
|
||||
if (x < 0) {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
sjcl.codec.hex = {
|
||||
/** Convert from a bitArray to a hex string. */
|
||||
fromBits: function (arr) {
|
||||
var out = "", i, x;
|
||||
var out = "", i;
|
||||
for (i=0; i<arr.length; i++) {
|
||||
out += ((arr[i]|0)+0xF00000000000).toString(16).substr(4);
|
||||
}
|
||||
|
||||
@@ -15,13 +15,13 @@
|
||||
* @param {String} plaintext The data to encrypt.
|
||||
* @param {Object} [params] The parameters including tag, iv and salt.
|
||||
* @param {Object} [rp] A returned version with filled-in parameters.
|
||||
* @return {String} The ciphertext.
|
||||
* @return {Object} The cipher raw data.
|
||||
* @throws {sjcl.exception.invalid} if a parameter is invalid.
|
||||
*/
|
||||
encrypt: function (password, plaintext, params, rp) {
|
||||
_encrypt: function (password, plaintext, params, rp) {
|
||||
params = params || {};
|
||||
rp = rp || {};
|
||||
|
||||
|
||||
var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4,0) },
|
||||
j.defaults), tmp, prp, adata;
|
||||
j._add(p, params);
|
||||
@@ -32,7 +32,7 @@
|
||||
if (typeof p.iv === "string") {
|
||||
p.iv = sjcl.codec.base64.toBits(p.iv);
|
||||
}
|
||||
|
||||
|
||||
if (!sjcl.mode[p.mode] ||
|
||||
!sjcl.cipher[p.cipher] ||
|
||||
(typeof password === "string" && p.iter <= 100) ||
|
||||
@@ -41,7 +41,7 @@
|
||||
(p.iv.length < 2 || p.iv.length > 4)) {
|
||||
throw new sjcl.exception.invalid("json encrypt: invalid parameters");
|
||||
}
|
||||
|
||||
|
||||
if (typeof password === "string") {
|
||||
tmp = sjcl.misc.cachedPbkdf2(password, p);
|
||||
password = tmp.key.slice(0,p.ks/32);
|
||||
@@ -58,39 +58,52 @@
|
||||
adata = sjcl.codec.utf8String.toBits(adata);
|
||||
}
|
||||
prp = new sjcl.cipher[p.cipher](password);
|
||||
|
||||
|
||||
/* return the json data */
|
||||
j._add(rp, p);
|
||||
rp.key = password;
|
||||
|
||||
|
||||
/* do the encryption */
|
||||
p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, adata, p.ts);
|
||||
|
||||
|
||||
//return j.encode(j._subtract(p, j.defaults));
|
||||
return p;
|
||||
},
|
||||
|
||||
/** Simple encryption function.
|
||||
* @param {String|bitArray} password The password or key.
|
||||
* @param {String} plaintext The data to encrypt.
|
||||
* @param {Object} [params] The parameters including tag, iv and salt.
|
||||
* @param {Object} [rp] A returned version with filled-in parameters.
|
||||
* @return {String} The ciphertext serialized data.
|
||||
* @throws {sjcl.exception.invalid} if a parameter is invalid.
|
||||
*/
|
||||
encrypt: function (password, plaintext, params, rp) {
|
||||
var j = sjcl.json, p = j._encrypt.apply(j, arguments);
|
||||
return j.encode(p);
|
||||
},
|
||||
|
||||
|
||||
/** Simple decryption function.
|
||||
* @param {String|bitArray} password The password or key.
|
||||
* @param {String} ciphertext The ciphertext to decrypt.
|
||||
* @param {Object} ciphertext The cipher raw data to decrypt.
|
||||
* @param {Object} [params] Additional non-default parameters.
|
||||
* @param {Object} [rp] A returned object with filled parameters.
|
||||
* @return {String} The plaintext.
|
||||
* @throws {sjcl.exception.invalid} if a parameter is invalid.
|
||||
* @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.
|
||||
*/
|
||||
decrypt: function (password, ciphertext, params, rp) {
|
||||
_decrypt: function (password, ciphertext, params, rp) {
|
||||
params = params || {};
|
||||
rp = rp || {};
|
||||
|
||||
var j = sjcl.json, p = j._add(j._add(j._add({},j.defaults),j.decode(ciphertext)), params, true), ct, tmp, prp, adata=p.adata;
|
||||
|
||||
var j = sjcl.json, p = j._add(j._add(j._add({},j.defaults),ciphertext), params, true), ct, tmp, prp, adata=p.adata;
|
||||
if (typeof p.salt === "string") {
|
||||
p.salt = sjcl.codec.base64.toBits(p.salt);
|
||||
}
|
||||
if (typeof p.iv === "string") {
|
||||
p.iv = sjcl.codec.base64.toBits(p.iv);
|
||||
}
|
||||
|
||||
|
||||
if (!sjcl.mode[p.mode] ||
|
||||
!sjcl.cipher[p.cipher] ||
|
||||
(typeof password === "string" && p.iter <= 100) ||
|
||||
@@ -100,7 +113,7 @@
|
||||
(p.iv.length < 2 || p.iv.length > 4)) {
|
||||
throw new sjcl.exception.invalid("json decrypt: invalid parameters");
|
||||
}
|
||||
|
||||
|
||||
if (typeof password === "string") {
|
||||
tmp = sjcl.misc.cachedPbkdf2(password, p);
|
||||
password = tmp.key.slice(0,p.ks/32);
|
||||
@@ -112,15 +125,33 @@
|
||||
adata = sjcl.codec.utf8String.toBits(adata);
|
||||
}
|
||||
prp = new sjcl.cipher[p.cipher](password);
|
||||
|
||||
|
||||
/* do the decryption */
|
||||
ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, adata, p.ts);
|
||||
|
||||
|
||||
/* return the json data */
|
||||
j._add(rp, p);
|
||||
rp.key = password;
|
||||
|
||||
return sjcl.codec.utf8String.fromBits(ct);
|
||||
|
||||
if (params.raw === 1) {
|
||||
return ct;
|
||||
} else {
|
||||
return sjcl.codec.utf8String.fromBits(ct);
|
||||
}
|
||||
},
|
||||
|
||||
/** Simple decryption function.
|
||||
* @param {String|bitArray} password The password or key.
|
||||
* @param {String} ciphertext The ciphertext to decrypt.
|
||||
* @param {Object} [params] Additional non-default parameters.
|
||||
* @param {Object} [rp] A returned object with filled parameters.
|
||||
* @return {String} The plaintext.
|
||||
* @throws {sjcl.exception.invalid} if a parameter is invalid.
|
||||
* @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.
|
||||
*/
|
||||
decrypt: function (password, ciphertext, params, rp) {
|
||||
var j = sjcl.json;
|
||||
return j._decrypt(password, j.decode(ciphertext), params, rp);
|
||||
},
|
||||
|
||||
/** Encode a flat structure into a JSON string.
|
||||
@@ -138,23 +169,23 @@
|
||||
}
|
||||
out += comma + '"' + i + '":';
|
||||
comma = ',';
|
||||
|
||||
|
||||
switch (typeof obj[i]) {
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
out += obj[i];
|
||||
break;
|
||||
|
||||
case 'string':
|
||||
out += '"' + escape(obj[i]) + '"';
|
||||
break;
|
||||
|
||||
case 'object':
|
||||
out += '"' + sjcl.codec.base64.fromBits(obj[i],0) + '"';
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new sjcl.exception.bug("json encode: unsupported type");
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
out += obj[i];
|
||||
break;
|
||||
|
||||
case 'string':
|
||||
out += '"' + escape(obj[i]) + '"';
|
||||
break;
|
||||
|
||||
case 'object':
|
||||
out += '"' + sjcl.codec.base64.fromBits(obj[i],0) + '"';
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new sjcl.exception.bug("json encode: unsupported type");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -174,13 +205,15 @@
|
||||
}
|
||||
var a = str.replace(/^\{|\}$/g, '').split(/,/), out={}, i, m;
|
||||
for (i=0; i<a.length; i++) {
|
||||
if (!(m=a[i].match(/^(?:(["']?)([a-z][a-z0-9]*)\1):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i))) {
|
||||
if (!(m=a[i].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) {
|
||||
throw new sjcl.exception.invalid("json decode: this isn't json!");
|
||||
}
|
||||
if (m[3]) {
|
||||
out[m[2]] = parseInt(m[3],10);
|
||||
} else {
|
||||
} else if (m[4]) {
|
||||
out[m[2]] = m[2].match(/^(ct|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);
|
||||
} else if (m[5]) {
|
||||
out[m[2]] = m[5] === 'true';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
@@ -213,13 +246,13 @@
|
||||
*/
|
||||
_subtract: function (plus, minus) {
|
||||
var out = {}, i;
|
||||
|
||||
|
||||
for (i in plus) {
|
||||
if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {
|
||||
out[i] = plus[i];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
@@ -262,7 +295,7 @@ sjcl.misc._pbkdf2Cache = {};
|
||||
|
||||
/** Cached PBKDF2 key derivation.
|
||||
* @param {String} password The password.
|
||||
* @param {Object} [params] The derivation params (iteration count and optional salt).
|
||||
* @param {Object} [obj] The derivation params (iteration count and optional salt).
|
||||
* @return {Object} The derived data in key, the salt in salt.
|
||||
*/
|
||||
sjcl.misc.cachedPbkdf2 = function (password, obj) {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/**
|
||||
* base class for all ecc operations.
|
||||
*/
|
||||
sjcl.ecc = {};
|
||||
|
||||
/**
|
||||
@@ -11,8 +14,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;
|
||||
@@ -144,7 +155,9 @@ sjcl.ecc.pointJac.prototype = {
|
||||
a = y2.mul(this.x.mul(4)),
|
||||
b = y2.square().mul(8),
|
||||
z2 = this.z.square(),
|
||||
c = this.x.sub(z2).mul(3).mul(this.x.add(z2)),
|
||||
c = this.curve.a.toString() == (new sjcl.bn(-3)).toString() ?
|
||||
this.x.sub(z2).mul(3).mul(this.x.add(z2)) :
|
||||
this.x.square().mul(3).add(z2.square().mul(this.curve.a)),
|
||||
x = c.square().subM(a).subM(a),
|
||||
y = a.sub(x).mul(c).subM(b),
|
||||
z = this.y.add(this.y).mul(this.z);
|
||||
@@ -154,7 +167,7 @@ sjcl.ecc.pointJac.prototype = {
|
||||
/**
|
||||
* Returns a copy of this point converted to affine coordinates.
|
||||
* @return {sjcl.ecc.point} The converted point.
|
||||
*/
|
||||
*/
|
||||
toAffine: function() {
|
||||
if (this.isIdentity || this.z.equals(0)) {
|
||||
return new sjcl.ecc.point(this.curve);
|
||||
@@ -242,7 +255,7 @@ sjcl.ecc.pointJac.prototype = {
|
||||
*/
|
||||
sjcl.ecc.curve = function(Field, r, a, b, x, y) {
|
||||
this.field = Field;
|
||||
this.r = Field.prototype.modulus.sub(r);
|
||||
this.r = new sjcl.bn(r);
|
||||
this.a = new Field(a);
|
||||
this.b = new Field(b);
|
||||
this.G = new sjcl.ecc.point(this, new Field(x), new Field(y));
|
||||
@@ -261,7 +274,7 @@ sjcl.ecc.curve.prototype.fromBits = function (bits) {
|
||||
sjcl.ecc.curves = {
|
||||
c192: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p192,
|
||||
"0x662107c8eb94364e4b2dd7ce",
|
||||
"0xffffffffffffffffffffffff99def836146bc9b1b4d22831",
|
||||
-3,
|
||||
"0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
|
||||
"0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
|
||||
@@ -269,7 +282,7 @@ sjcl.ecc.curves = {
|
||||
|
||||
c224: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p224,
|
||||
"0xe95c1f470fc1ec22d6baa3a3d5c4",
|
||||
"0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d",
|
||||
-3,
|
||||
"0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4",
|
||||
"0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21",
|
||||
@@ -277,7 +290,7 @@ sjcl.ecc.curves = {
|
||||
|
||||
c256: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p256,
|
||||
"0x4319055358e8617b0c46353d039cdaae",
|
||||
"0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
|
||||
-3,
|
||||
"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
|
||||
"0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
|
||||
@@ -285,71 +298,135 @@ sjcl.ecc.curves = {
|
||||
|
||||
c384: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p384,
|
||||
"0x389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68c",
|
||||
"0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973",
|
||||
-3,
|
||||
"0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef",
|
||||
"0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
|
||||
"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
|
||||
"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),
|
||||
|
||||
k192: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p192k,
|
||||
"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
|
||||
0,
|
||||
3,
|
||||
"0xdb4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
|
||||
"0x9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"),
|
||||
|
||||
k224: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p224k,
|
||||
"0x010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7",
|
||||
0,
|
||||
5,
|
||||
"0xa1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c",
|
||||
"0x7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5"),
|
||||
|
||||
k256: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p256k,
|
||||
"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
|
||||
0,
|
||||
7,
|
||||
"0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
||||
"0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
||||
|
||||
};
|
||||
|
||||
|
||||
/* Diffie-Hellman-like public-key system */
|
||||
sjcl.ecc._dh = function(cn) {
|
||||
sjcl.ecc[cn] = {
|
||||
/** @constructor */
|
||||
publicKey: function(curve, point) {
|
||||
this._curve = curve;
|
||||
this._curveBitLength = curve.r.bitLength();
|
||||
if (point instanceof Array) {
|
||||
this._point = curve.fromBits(point);
|
||||
} else {
|
||||
this._point = point;
|
||||
}
|
||||
|
||||
this.get = function() {
|
||||
var pointbits = this._point.toBits();
|
||||
var len = sjcl.bitArray.bitLength(pointbits);
|
||||
var x = sjcl.bitArray.bitSlice(pointbits, 0, len/2);
|
||||
var y = sjcl.bitArray.bitSlice(pointbits, len/2);
|
||||
return { x: x, y: y };
|
||||
}
|
||||
},
|
||||
|
||||
/** @constructor */
|
||||
secretKey: function(curve, exponent) {
|
||||
this._curve = curve;
|
||||
this._curveBitLength = curve.r.bitLength();
|
||||
this._exponent = exponent;
|
||||
|
||||
this.get = function() {
|
||||
return this._exponent.toBits();
|
||||
}
|
||||
},
|
||||
|
||||
/** @constructor */
|
||||
generateKeys: function(curve, paranoia, sec) {
|
||||
if (curve === undefined) {
|
||||
curve = 256;
|
||||
}
|
||||
if (typeof curve === "number") {
|
||||
curve = sjcl.ecc.curves['c'+curve];
|
||||
if (curve === undefined) {
|
||||
throw new sjcl.exception.invalid("no such curve");
|
||||
}
|
||||
}
|
||||
if (sec === undefined) {
|
||||
var sec = sjcl.bn.random(curve.r, paranoia);
|
||||
}
|
||||
var pub = curve.G.mult(sec);
|
||||
return { pub: new sjcl.ecc[cn].publicKey(curve, pub),
|
||||
sec: new sjcl.ecc[cn].secretKey(curve, sec) };
|
||||
/** our basicKey classes
|
||||
*/
|
||||
sjcl.ecc.basicKey = {
|
||||
/** ecc publicKey.
|
||||
* @constructor
|
||||
* @param {curve} curve the elliptic curve
|
||||
* @param {point} point the point on the curve
|
||||
*/
|
||||
publicKey: function(curve, point) {
|
||||
this._curve = curve;
|
||||
this._curveBitLength = curve.r.bitLength();
|
||||
if (point instanceof Array) {
|
||||
this._point = curve.fromBits(point);
|
||||
} else {
|
||||
this._point = point;
|
||||
}
|
||||
};
|
||||
|
||||
/** get this keys point data
|
||||
* @return x and y as bitArrays
|
||||
*/
|
||||
this.get = function() {
|
||||
var pointbits = this._point.toBits();
|
||||
var len = sjcl.bitArray.bitLength(pointbits);
|
||||
var x = sjcl.bitArray.bitSlice(pointbits, 0, len/2);
|
||||
var y = sjcl.bitArray.bitSlice(pointbits, len/2);
|
||||
return { x: x, y: y };
|
||||
};
|
||||
},
|
||||
|
||||
/** ecc secretKey
|
||||
* @constructor
|
||||
* @param {curve} curve the elliptic curve
|
||||
* @param exponent
|
||||
*/
|
||||
secretKey: function(curve, exponent) {
|
||||
this._curve = curve;
|
||||
this._curveBitLength = curve.r.bitLength();
|
||||
this._exponent = exponent;
|
||||
|
||||
/** get this keys exponent data
|
||||
* @return {bitArray} exponent
|
||||
*/
|
||||
this.get = function () {
|
||||
return this._exponent.toBits();
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.ecc._dh("elGamal");
|
||||
/** @private */
|
||||
sjcl.ecc.basicKey.generateKeys = function(cn) {
|
||||
return function generateKeys(curve, paranoia, sec) {
|
||||
curve = curve || 256;
|
||||
|
||||
if (typeof curve === "number") {
|
||||
curve = sjcl.ecc.curves['c'+curve];
|
||||
if (curve === undefined) {
|
||||
throw new sjcl.exception.invalid("no such curve");
|
||||
}
|
||||
}
|
||||
sec = sec || sjcl.bn.random(curve.r, paranoia);
|
||||
|
||||
var pub = curve.G.mult(sec);
|
||||
return { pub: new sjcl.ecc[cn].publicKey(curve, pub),
|
||||
sec: new sjcl.ecc[cn].secretKey(curve, sec) };
|
||||
};
|
||||
};
|
||||
|
||||
/** elGamal keys */
|
||||
sjcl.ecc.elGamal = {
|
||||
/** generate keys
|
||||
* @function
|
||||
* @param curve
|
||||
* @param {int} paranoia Paranoia for generation (default 6)
|
||||
* @param {secretKey} sec secret Key to use. used to get the publicKey for ones secretKey
|
||||
*/
|
||||
generateKeys: sjcl.ecc.basicKey.generateKeys("elGamal"),
|
||||
/** elGamal publicKey.
|
||||
* @constructor
|
||||
* @augments sjcl.ecc.basicKey.publicKey
|
||||
*/
|
||||
publicKey: function (curve, point) {
|
||||
sjcl.ecc.basicKey.publicKey.apply(this, arguments);
|
||||
},
|
||||
/** elGamal secretKey
|
||||
* @constructor
|
||||
* @augments sjcl.ecc.basicKey.secretKey
|
||||
*/
|
||||
secretKey: function (curve, exponent) {
|
||||
sjcl.ecc.basicKey.secretKey.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.ecc.elGamal.publicKey.prototype = {
|
||||
/** Kem function of elGamal Public Key
|
||||
* @param paranoia paranoia to use for randomization.
|
||||
* @return {object} key and tag. unkem(tag) with the corresponding secret key results in the key returned.
|
||||
*/
|
||||
kem: function(paranoia) {
|
||||
var sec = sjcl.bn.random(this._curve.r, paranoia),
|
||||
tag = this._curve.G.mult(sec).toBits(),
|
||||
@@ -359,34 +436,58 @@ sjcl.ecc.elGamal.publicKey.prototype = {
|
||||
};
|
||||
|
||||
sjcl.ecc.elGamal.secretKey.prototype = {
|
||||
/** UnKem function of elGamal Secret Key
|
||||
* @param {bitArray} tag The Tag to decrypt.
|
||||
* @return {bitArray} decrypted key.
|
||||
*/
|
||||
unkem: function(tag) {
|
||||
return sjcl.hash.sha256.hash(this._curve.fromBits(tag).mult(this._exponent).toBits());
|
||||
},
|
||||
|
||||
/** Diffie-Hellmann function
|
||||
* @param {elGamal.publicKey} pk The Public Key to do Diffie-Hellmann with
|
||||
* @return {bitArray} diffie-hellmann result for this key combination.
|
||||
*/
|
||||
dh: function(pk) {
|
||||
return sjcl.hash.sha256.hash(pk._point.mult(this._exponent).toBits());
|
||||
}
|
||||
},
|
||||
|
||||
/** Diffie-Hellmann function, compatible with Java generateSecret
|
||||
* @param {elGamal.publicKey} pk The Public Key to do Diffie-Hellmann with
|
||||
* @return {bitArray} undigested X value, diffie-hellmann result for this key combination,
|
||||
* compatible with Java generateSecret().
|
||||
*/
|
||||
dhJavaEc: function(pk) {
|
||||
return pk._point.mult(this._exponent).x.toBits();
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.ecc._dh("ecdsa");
|
||||
|
||||
sjcl.ecc.ecdsa.secretKey.prototype = {
|
||||
sign: function(hash, paranoia, fakeLegacyVersion, fixedKForTesting) {
|
||||
if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {
|
||||
hash = sjcl.bitArray.clamp(hash, this._curveBitLength);
|
||||
}
|
||||
var R = this._curve.r,
|
||||
l = R.bitLength(),
|
||||
k = fixedKForTesting || sjcl.bn.random(R.sub(1), paranoia).add(1),
|
||||
r = this._curve.G.mult(k).x.mod(R),
|
||||
ss = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)),
|
||||
s = fakeLegacyVersion ? ss.inverseMod(R).mul(k).mod(R)
|
||||
: ss.mul(k.inverseMod(R)).mod(R);
|
||||
return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
|
||||
}
|
||||
/** ecdsa keys */
|
||||
sjcl.ecc.ecdsa = {
|
||||
/** generate keys
|
||||
* @function
|
||||
* @param curve
|
||||
* @param {int} paranoia Paranoia for generation (default 6)
|
||||
* @param {secretKey} sec secret Key to use. used to get the publicKey for ones secretKey
|
||||
*/
|
||||
generateKeys: sjcl.ecc.basicKey.generateKeys("ecdsa")
|
||||
};
|
||||
|
||||
/** ecdsa publicKey.
|
||||
* @constructor
|
||||
* @augments sjcl.ecc.basicKey.publicKey
|
||||
*/
|
||||
sjcl.ecc.ecdsa.publicKey = function (curve, point) {
|
||||
sjcl.ecc.basicKey.publicKey.apply(this, arguments);
|
||||
};
|
||||
|
||||
/** specific functions for ecdsa publicKey. */
|
||||
sjcl.ecc.ecdsa.publicKey.prototype = {
|
||||
/** Diffie-Hellmann function
|
||||
* @param {bitArray} hash hash to verify.
|
||||
* @param {bitArray} rs signature bitArray.
|
||||
* @param {boolean} fakeLegacyVersion use old legacy version
|
||||
*/
|
||||
verify: function(hash, rs, fakeLegacyVersion) {
|
||||
if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {
|
||||
hash = sjcl.bitArray.clamp(hash, this._curveBitLength);
|
||||
@@ -410,3 +511,33 @@ sjcl.ecc.ecdsa.publicKey.prototype = {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
/** ecdsa secretKey
|
||||
* @constructor
|
||||
* @augments sjcl.ecc.basicKey.publicKey
|
||||
*/
|
||||
sjcl.ecc.ecdsa.secretKey = function (curve, exponent) {
|
||||
sjcl.ecc.basicKey.secretKey.apply(this, arguments);
|
||||
};
|
||||
|
||||
/** specific functions for ecdsa secretKey. */
|
||||
sjcl.ecc.ecdsa.secretKey.prototype = {
|
||||
/** Diffie-Hellmann function
|
||||
* @param {bitArray} hash hash to sign.
|
||||
* @param {int} paranoia paranoia for random number generation
|
||||
* @param {boolean} fakeLegacyVersion use old legacy version
|
||||
*/
|
||||
sign: function(hash, paranoia, fakeLegacyVersion, fixedKForTesting) {
|
||||
if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {
|
||||
hash = sjcl.bitArray.clamp(hash, this._curveBitLength);
|
||||
}
|
||||
var R = this._curve.r,
|
||||
l = R.bitLength(),
|
||||
k = fixedKForTesting || sjcl.bn.random(R.sub(1), paranoia).add(1),
|
||||
r = this._curve.G.mult(k).x.mod(R),
|
||||
ss = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)),
|
||||
s = fakeLegacyVersion ? ss.inverseMod(R).mul(k).mod(R)
|
||||
: ss.mul(k.inverseMod(R)).mod(R);
|
||||
return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -120,7 +120,7 @@ sjcl.mode.gcm = {
|
||||
* @param {Number} tlen The length of the tag, in bits.
|
||||
*/
|
||||
_ctrMode: function(encrypt, prf, data, adata, iv, tlen) {
|
||||
var H, J0, S0, enc, i, ctr, tag, last, l, bl, abl, ivbl, w=sjcl.bitArray, xor=w._xor4;
|
||||
var H, J0, S0, enc, i, ctr, tag, last, l, bl, abl, ivbl, w=sjcl.bitArray;
|
||||
|
||||
// Calculate data lengths
|
||||
l = data.length;
|
||||
|
||||
@@ -27,13 +27,35 @@ sjcl.misc.hmac = function (key, Hash) {
|
||||
|
||||
this._baseHash[0].update(exKey[0]);
|
||||
this._baseHash[1].update(exKey[1]);
|
||||
this._resultHash = new Hash(this._baseHash[0]);
|
||||
};
|
||||
|
||||
/** HMAC with the specified hash function. Also called encrypt since it's a prf.
|
||||
* @param {bitArray|String} data The data to mac.
|
||||
*/
|
||||
sjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data) {
|
||||
var w = new (this._hash)(this._baseHash[0]).update(data).finalize();
|
||||
return new (this._hash)(this._baseHash[1]).update(w).finalize();
|
||||
if (!this._updated) {
|
||||
this.update(data);
|
||||
return this.digest(data);
|
||||
} else {
|
||||
throw new sjcl.exception.invalid("encrypt on already updated hmac called!");
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.misc.hmac.prototype.reset = function () {
|
||||
this._resultHash = new this._hash(this._baseHash[0]);
|
||||
this._updated = false;
|
||||
};
|
||||
|
||||
sjcl.misc.hmac.prototype.update = function (data) {
|
||||
this._updated = true;
|
||||
this._resultHash.update(data);
|
||||
};
|
||||
|
||||
sjcl.misc.hmac.prototype.digest = function () {
|
||||
var w = this._resultHash.finalize(), result = new (this._hash)(this._baseHash[1]).update(w).finalize();
|
||||
|
||||
this.reset();
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -12,7 +12,7 @@
|
||||
* This is the method specified by RSA's PKCS #5 standard.
|
||||
*
|
||||
* @param {bitArray|String} password The password.
|
||||
* @param {bitArray} salt The salt. Should have lots of entropy.
|
||||
* @param {bitArray|String} salt The salt. Should have lots of entropy.
|
||||
* @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure.
|
||||
* @param {Number} [length] The length of the derived key. Defaults to the
|
||||
output size of the hash function.
|
||||
@@ -30,6 +30,10 @@ sjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {
|
||||
password = sjcl.codec.utf8String.toBits(password);
|
||||
}
|
||||
|
||||
if (typeof salt === "string") {
|
||||
salt = sjcl.codec.utf8String.toBits(salt);
|
||||
}
|
||||
|
||||
Prff = Prff || sjcl.misc.hmac;
|
||||
|
||||
var prf = new Prff(password),
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
* @author Michael Brooks
|
||||
*/
|
||||
|
||||
/** @constructor
|
||||
* @class Random number generator
|
||||
*
|
||||
* @description
|
||||
* <b>Use sjcl.random as a singleton for this class!</b>
|
||||
* <p>
|
||||
* This random number generator is a derivative of Ferguson and Schneier's
|
||||
* generator Fortuna. It collects entropy from various events into several
|
||||
@@ -74,10 +75,11 @@ sjcl.prng = function(defaultParanoia) {
|
||||
this._PARANOIA_LEVELS = [0,48,64,96,128,192,256,384,512,768,1024];
|
||||
this._MILLISECONDS_PER_RESEED = 30000;
|
||||
this._BITS_PER_RESEED = 80;
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.prng.prototype = {
|
||||
/** Generate several random words, and return them in an array
|
||||
/** Generate several random words, and return them in an array.
|
||||
* A word consists of 32 bits (4 bytes)
|
||||
* @param {Number} nwords The number of words to generate.
|
||||
*/
|
||||
randomWords: function (nwords, paranoia) {
|
||||
@@ -102,7 +104,11 @@ sjcl.prng.prototype = {
|
||||
return out.slice(0,nwords);
|
||||
},
|
||||
|
||||
setDefaultParanoia: function (paranoia) {
|
||||
setDefaultParanoia: function (paranoia, allowZeroParanoia) {
|
||||
if (paranoia === 0 && allowZeroParanoia !== "Setting paranoia=0 will ruin your security; use it only for testing") {
|
||||
throw "Setting paranoia=0 will ruin your security; use it only for testing";
|
||||
}
|
||||
|
||||
this._defaultParanoia = paranoia;
|
||||
},
|
||||
|
||||
@@ -119,7 +125,7 @@ sjcl.prng.prototype = {
|
||||
i, tmp,
|
||||
t = (new Date()).valueOf(),
|
||||
robin = this._robins[source],
|
||||
oldReady = this.isReady(), err = 0;
|
||||
oldReady = this.isReady(), err = 0, objName;
|
||||
|
||||
id = this._collectorIds[source];
|
||||
if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }
|
||||
@@ -137,7 +143,7 @@ sjcl.prng.prototype = {
|
||||
break;
|
||||
|
||||
case "object":
|
||||
var objName = Object.prototype.toString.call(data);
|
||||
objName = Object.prototype.toString.call(data);
|
||||
if (objName === "[object Uint32Array]") {
|
||||
tmp = [];
|
||||
for (i = 0; i < data.length; i++) {
|
||||
@@ -149,7 +155,7 @@ sjcl.prng.prototype = {
|
||||
err = 1;
|
||||
}
|
||||
for (i=0; i<data.length && !err; i++) {
|
||||
if (typeof(data[i]) != "number") {
|
||||
if (typeof(data[i]) !== "number") {
|
||||
err = 1;
|
||||
}
|
||||
}
|
||||
@@ -234,14 +240,25 @@ sjcl.prng.prototype = {
|
||||
startCollectors: function () {
|
||||
if (this._collectorsStarted) { return; }
|
||||
|
||||
this._eventListener = {
|
||||
loadTimeCollector: this._bind(this._loadTimeCollector),
|
||||
mouseCollector: this._bind(this._mouseCollector),
|
||||
keyboardCollector: this._bind(this._keyboardCollector),
|
||||
accelerometerCollector: this._bind(this._accelerometerCollector),
|
||||
touchCollector: this._bind(this._touchCollector)
|
||||
};
|
||||
|
||||
if (window.addEventListener) {
|
||||
window.addEventListener("load", this._loadTimeCollector, false);
|
||||
window.addEventListener("mousemove", this._mouseCollector, false);
|
||||
window.addEventListener("load", this._eventListener.loadTimeCollector, false);
|
||||
window.addEventListener("mousemove", this._eventListener.mouseCollector, false);
|
||||
window.addEventListener("keypress", this._eventListener.keyboardCollector, false);
|
||||
window.addEventListener("devicemotion", this._eventListener.accelerometerCollector, false);
|
||||
window.addEventListener("touchmove", this._eventListener.touchCollector, false);
|
||||
} else if (document.attachEvent) {
|
||||
document.attachEvent("onload", this._loadTimeCollector);
|
||||
document.attachEvent("onmousemove", this._mouseCollector);
|
||||
}
|
||||
else {
|
||||
document.attachEvent("onload", this._eventListener.loadTimeCollector);
|
||||
document.attachEvent("onmousemove", this._eventListener.mouseCollector);
|
||||
document.attachEvent("keypress", this._eventListener.keyboardCollector);
|
||||
} else {
|
||||
throw new sjcl.exception.bug("can't attach event");
|
||||
}
|
||||
|
||||
@@ -253,12 +270,17 @@ sjcl.prng.prototype = {
|
||||
if (!this._collectorsStarted) { return; }
|
||||
|
||||
if (window.removeEventListener) {
|
||||
window.removeEventListener("load", this._loadTimeCollector, false);
|
||||
window.removeEventListener("mousemove", this._mouseCollector, false);
|
||||
} else if (window.detachEvent) {
|
||||
window.detachEvent("onload", this._loadTimeCollector);
|
||||
window.detachEvent("onmousemove", this._mouseCollector);
|
||||
window.removeEventListener("load", this._eventListener.loadTimeCollector, false);
|
||||
window.removeEventListener("mousemove", this._eventListener.mouseCollector, false);
|
||||
window.removeEventListener("keypress", this._eventListener.keyboardCollector, false);
|
||||
window.removeEventListener("devicemotion", this._eventListener.accelerometerCollector, false);
|
||||
window.removeEventListener("touchmove", this._eventListener.touchCollector, false);
|
||||
} else if (document.detachEvent) {
|
||||
document.detachEvent("onload", this._eventListener.loadTimeCollector);
|
||||
document.detachEvent("onmousemove", this._eventListener.mouseCollector);
|
||||
document.detachEvent("keypress", this._eventListener.keyboardCollector);
|
||||
}
|
||||
|
||||
this._collectorsStarted = false;
|
||||
},
|
||||
|
||||
@@ -275,23 +297,30 @@ sjcl.prng.prototype = {
|
||||
/** remove an event listener for progress or seeded-ness */
|
||||
removeEventListener: function (name, cb) {
|
||||
var i, j, cbs=this._callbacks[name], jsTemp=[];
|
||||
|
||||
|
||||
/* I'm not sure if this is necessary; in C++, iterating over a
|
||||
* collection and modifying it at the same time is a no-no.
|
||||
*/
|
||||
|
||||
|
||||
for (j in cbs) {
|
||||
if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
|
||||
if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
|
||||
jsTemp.push(j);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (i=0; i<jsTemp.length; i++) {
|
||||
j = jsTemp[i];
|
||||
delete cbs[j];
|
||||
}
|
||||
},
|
||||
|
||||
_bind: function (func) {
|
||||
var that = this;
|
||||
return function () {
|
||||
func.apply(that, arguments);
|
||||
};
|
||||
},
|
||||
|
||||
/** Generate 4 random words, no reseed, no gate.
|
||||
* @private
|
||||
*/
|
||||
@@ -363,44 +392,131 @@ sjcl.prng.prototype = {
|
||||
this._reseed(reseedData);
|
||||
},
|
||||
|
||||
_keyboardCollector: function () {
|
||||
this._addCurrentTimeToEntropy(1);
|
||||
},
|
||||
|
||||
_mouseCollector: function (ev) {
|
||||
var x = ev.x || ev.clientX || ev.offsetX || 0, y = ev.y || ev.clientY || ev.offsetY || 0;
|
||||
sjcl.random.addEntropy([x,y], 2, "mouse");
|
||||
var x, y;
|
||||
|
||||
try {
|
||||
x = ev.x || ev.clientX || ev.offsetX || 0;
|
||||
y = ev.y || ev.clientY || ev.offsetY || 0;
|
||||
} catch (err) {
|
||||
// Event originated from a secure element. No mouse position available.
|
||||
x = 0;
|
||||
y = 0;
|
||||
}
|
||||
|
||||
if (x != 0 && y!= 0) {
|
||||
sjcl.random.addEntropy([x,y], 2, "mouse");
|
||||
}
|
||||
|
||||
this._addCurrentTimeToEntropy(0);
|
||||
},
|
||||
|
||||
_touchCollector: function(ev) {
|
||||
var touch = ev.touches[0] || ev.changedTouches[0];
|
||||
var x = touch.pageX || touch.clientX,
|
||||
y = touch.pageY || touch.clientY;
|
||||
|
||||
sjcl.random.addEntropy([x,y],1,"touch");
|
||||
|
||||
this._addCurrentTimeToEntropy(0);
|
||||
},
|
||||
|
||||
_loadTimeCollector: function (ev) {
|
||||
sjcl.random.addEntropy((new Date()).valueOf(), 2, "loadtime");
|
||||
_loadTimeCollector: function () {
|
||||
this._addCurrentTimeToEntropy(2);
|
||||
},
|
||||
|
||||
|
||||
_addCurrentTimeToEntropy: function (estimatedEntropy) {
|
||||
if (typeof window !== 'undefined' && window.performance && typeof window.performance.now === "function") {
|
||||
//how much entropy do we want to add here?
|
||||
sjcl.random.addEntropy(window.performance.now(), estimatedEntropy, "loadtime");
|
||||
} else {
|
||||
sjcl.random.addEntropy((new Date()).valueOf(), estimatedEntropy, "loadtime");
|
||||
}
|
||||
},
|
||||
_accelerometerCollector: function (ev) {
|
||||
var ac = ev.accelerationIncludingGravity.x||ev.accelerationIncludingGravity.y||ev.accelerationIncludingGravity.z;
|
||||
if(window.orientation){
|
||||
var or = window.orientation;
|
||||
if (typeof or === "number") {
|
||||
sjcl.random.addEntropy(or, 1, "accelerometer");
|
||||
}
|
||||
}
|
||||
if (ac) {
|
||||
sjcl.random.addEntropy(ac, 2, "accelerometer");
|
||||
}
|
||||
this._addCurrentTimeToEntropy(0);
|
||||
},
|
||||
|
||||
_fireEvent: function (name, arg) {
|
||||
var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];
|
||||
/* TODO: there is a race condition between removing collectors and firing them */
|
||||
/* TODO: there is a race condition between removing collectors and firing them */
|
||||
|
||||
/* I'm not sure if this is necessary; in C++, iterating over a
|
||||
* collection and modifying it at the same time is a no-no.
|
||||
*/
|
||||
|
||||
|
||||
for (j in cbs) {
|
||||
if (cbs.hasOwnProperty(j)) {
|
||||
if (cbs.hasOwnProperty(j)) {
|
||||
cbsTemp.push(cbs[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (j=0; j<cbsTemp.length; j++) {
|
||||
cbsTemp[j](arg);
|
||||
cbsTemp[j](arg);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** an instance for the prng.
|
||||
* @see sjcl.prng
|
||||
*/
|
||||
sjcl.random = new sjcl.prng(6);
|
||||
|
||||
(function(){
|
||||
try {
|
||||
// get cryptographically strong entropy in Webkit
|
||||
var ab = new Uint32Array(32);
|
||||
crypto.getRandomValues(ab);
|
||||
sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues");
|
||||
} catch (e) {
|
||||
// no getRandomValues :-(
|
||||
// function for getting nodejs crypto module. catches and ignores errors.
|
||||
function getCryptoModule() {
|
||||
try {
|
||||
return require('crypto');
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
var buf, crypt, ab;
|
||||
|
||||
// get cryptographically strong entropy depending on runtime environment
|
||||
if (typeof module !== 'undefined' && module.exports && (crypt = getCryptoModule()) && crypt.randomBytes) {
|
||||
buf = crypt.randomBytes(1024/8);
|
||||
buf = new Uint32Array(new Uint8Array(buf).buffer);
|
||||
sjcl.random.addEntropy(buf, 1024, "crypto.randomBytes");
|
||||
|
||||
} else if (typeof window !== 'undefined' && typeof Uint32Array !== 'undefined') {
|
||||
ab = new Uint32Array(32);
|
||||
if (window.crypto && window.crypto.getRandomValues) {
|
||||
window.crypto.getRandomValues(ab);
|
||||
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
|
||||
window.msCrypto.getRandomValues(ab);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// get cryptographically strong entropy in Webkit
|
||||
sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues");
|
||||
|
||||
} else {
|
||||
// no getRandomValues :-(
|
||||
}
|
||||
} catch (e) {
|
||||
if (typeof window !== 'undefined' && window.console) {
|
||||
console.log("There was an error collecting entropy from the browser:");
|
||||
console.log(e);
|
||||
//we do not want the library to fail due to randomness not being maintained.
|
||||
}
|
||||
}
|
||||
}());
|
||||
|
||||
@@ -138,8 +138,7 @@ sjcl.hash.sha1.prototype = {
|
||||
_block:function (words) {
|
||||
var t, tmp, a, b, c, d, e,
|
||||
w = words.slice(0),
|
||||
h = this._h,
|
||||
k = this._key;
|
||||
h = this._h;
|
||||
|
||||
a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4];
|
||||
|
||||
|
||||
@@ -299,7 +299,7 @@ sjcl.hash.sha512.prototype = {
|
||||
t1h += chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
|
||||
t1l += krl;
|
||||
t1h += krh + ((t1l >>> 0) < (krl >>> 0) ? 1 : 0);
|
||||
t1l += wrl;
|
||||
t1l = t1l + wrl|0; // FF32..FF34 perf issue https://bugzilla.mozilla.org/show_bug.cgi?id=1054972
|
||||
t1h += wrh + ((t1l >>> 0) < (wrl >>> 0) ? 1 : 0);
|
||||
|
||||
// t2 = sigma0 + maj
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
"use strict";
|
||||
/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
|
||||
/*global document, window, escape, unescape */
|
||||
/*global document, window, escape, unescape, module, require, Uint32Array */
|
||||
|
||||
/** @namespace The Stanford Javascript Crypto Library, top-level namespace. */
|
||||
var sjcl = {
|
||||
@@ -68,6 +68,11 @@ var sjcl = {
|
||||
}
|
||||
};
|
||||
|
||||
if(typeof module != 'undefined' && module.exports){
|
||||
if(typeof module !== 'undefined' && module.exports){
|
||||
module.exports = sjcl;
|
||||
}
|
||||
if (typeof define === "function") {
|
||||
define([], function () {
|
||||
return sjcl;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
<h2>Key Derivation</h2>
|
||||
<div class="section">
|
||||
<div>
|
||||
<label for="salt"">Salt:</label>
|
||||
<label for="salt">Salt:</label>
|
||||
<a class="random floatright" href="javascript:randomize('salt',2,0)">random</a>
|
||||
</div>
|
||||
<input type="text" id="salt" class="wide hex" autocomplete="off" size="17" maxlength="35"/>
|
||||
|
||||
16
src/js/sjcl/package.json
Normal file
16
src/js/sjcl/package.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "sjcl",
|
||||
"version": "1.0.1",
|
||||
"description": "Stanford Javascript Crypto Library",
|
||||
"main": "sjcl.js",
|
||||
"author": "bitwiseshiftleft",
|
||||
"keywords": ["encryption", "high-level", "crypto"],
|
||||
"repository" : {
|
||||
"type": "git",
|
||||
"url": "https://github.com/bitwiseshiftleft/sjcl.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
},
|
||||
"engines": { "node": "*" }
|
||||
}
|
||||
@@ -1,48 +1,54 @@
|
||||
"use strict";function q(a){throw a;}var t=void 0,u=!1;var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
|
||||
"undefined"!=typeof module&&module.exports&&(module.exports=sjcl);
|
||||
sjcl.cipher.aes=function(a){this.j[0][0][0]||this.D();var b,c,d,e,f=this.j[0][4],g=this.j[1];b=a.length;var h=1;4!==b&&(6!==b&&8!==b)&&q(new sjcl.exception.invalid("invalid aes key size"));this.a=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
|
||||
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define&&define([],function(){return sjcl});
|
||||
sjcl.cipher.aes=function(a){this.k[0][0][0]||this.D();var b,c,d,e,f=this.k[0][4],g=this.k[1];b=a.length;var h=1;4!==b&&(6!==b&&8!==b)&&q(new sjcl.exception.invalid("invalid aes key size"));this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
|
||||
255]]};
|
||||
sjcl.cipher.aes.prototype={encrypt:function(a){return y(this,a,0)},decrypt:function(a){return y(this,a,1)},j:[[[],[],[],[],[]],[[],[],[],[],[]]],D:function(){var a=this.j[0],b=this.j[1],c=a[4],d=b[4],e,f,g,h=[],l=[],k,n,m,p;for(e=0;0x100>e;e++)l[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=k||1,g=l[g]||1){m=g^g<<1^g<<2^g<<3^g<<4;m=m>>8^m&255^99;c[f]=m;d[m]=f;n=h[e=h[k=h[f]]];p=0x1010101*n^0x10001*e^0x101*k^0x1010100*f;n=0x101*h[m]^0x1010100*m;for(e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8}for(e=
|
||||
sjcl.cipher.aes.prototype={encrypt:function(a){return y(this,a,0)},decrypt:function(a){return y(this,a,1)},k:[[[],[],[],[],[]],[[],[],[],[],[]]],D:function(){var a=this.k[0],b=this.k[1],c=a[4],d=b[4],e,f,g,h=[],l=[],k,n,m,p;for(e=0;0x100>e;e++)l[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=k||1,g=l[g]||1){m=g^g<<1^g<<2^g<<3^g<<4;m=m>>8^m&255^99;c[f]=m;d[m]=f;n=h[e=h[k=h[f]]];p=0x1010101*n^0x10001*e^0x101*k^0x1010100*f;n=0x101*h[m]^0x1010100*m;for(e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8}for(e=
|
||||
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
|
||||
function y(a,b,c){4!==b.length&&q(new sjcl.exception.invalid("invalid aes block size"));var d=a.a[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,l,k,n=d.length/4-2,m,p=4,s=[0,0,0,0];h=a.j[c];a=h[0];var r=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^r[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],l=a[f>>>24]^r[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],k=a[g>>>24]^r[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^r[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=l,g=k;for(m=0;4>
|
||||
function y(a,b,c){4!==b.length&&q(new sjcl.exception.invalid("invalid aes block size"));var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,l,k,n=d.length/4-2,m,p=4,s=[0,0,0,0];h=a.k[c];a=h[0];var r=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^r[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],l=a[f>>>24]^r[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],k=a[g>>>24]^r[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^r[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=l,g=k;for(m=0;4>
|
||||
m;m++)s[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return s}
|
||||
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.O(a.slice(b/32),32-(b&31)).slice(1);return c===t?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.O(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0===
|
||||
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.P(a.slice(b/32),32-(b&31)).slice(1);return c===t?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.P(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0===
|
||||
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b&=31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return u;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0===
|
||||
c},O:function(a,b,c,d){var e;e=0;for(d===t&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},k:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}};
|
||||
c},P:function(a,b,c,d){var e;e=0;for(d===t&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},l:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}};
|
||||
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>24),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
|
||||
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a+="00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
|
||||
sjcl.codec.base64={I:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d="",e=0,f=sjcl.codec.base64.I,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.I,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++)h=f.indexOf(a.charAt(d)),
|
||||
0>h&&q(new sjcl.exception.invalid("this isn't base64!")),26<e?(e-=26,c.push(g^h>>>e),g=h<<32-e):(e+=6,g^=h<<32-e);e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.a[0]||this.D();a?(this.q=a.q.slice(0),this.m=a.m.slice(0),this.g=a.g):this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
|
||||
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.q=this.M.slice(0);this.m=[];this.g=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.m=sjcl.bitArray.concat(this.m,a);b=this.g;a=this.g=b+sjcl.bitArray.bitLength(a);for(b=512+b&-512;b<=a;b+=512)z(this,c.splice(0,16));return this},finalize:function(){var a,b=this.m,c=this.q,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.g/
|
||||
4294967296));for(b.push(this.g|0);b.length;)z(this,b.splice(0,16));this.reset();return c},M:[],a:[],D:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}var b=0,c=2,d;a:for(;64>b;c++){for(d=2;d*d<=c;d++)if(0===c%d)continue a;8>b&&(this.M[b]=a(Math.pow(c,0.5)));this.a[b]=a(Math.pow(c,1/3));b++}}};
|
||||
function z(a,b){var c,d,e,f=b.slice(0),g=a.q,h=a.a,l=g[0],k=g[1],n=g[2],m=g[3],p=g[4],s=g[5],r=g[6],v=g[7];for(c=0;64>c;c++)16>c?d=f[c]:(d=f[c+1&15],e=f[c+14&15],d=f[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+f[c&15]+f[c+9&15]|0),d=d+v+(p>>>6^p>>>11^p>>>25^p<<26^p<<21^p<<7)+(r^p&(s^r))+h[c],v=r,r=s,s=p,p=m+d|0,m=n,n=k,k=l,l=d+(k&n^m&(k^n))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;g[0]=g[0]+l|0;g[1]=g[1]+k|0;g[2]=g[2]+n|0;g[3]=g[3]+m|0;g[4]=g[4]+p|0;g[5]=g[5]+s|0;g[6]=
|
||||
sjcl.codec.base64={J:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d="",e=0,f=sjcl.codec.base64.J,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.J,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++)h=f.indexOf(a.charAt(d)),
|
||||
0>h&&q(new sjcl.exception.invalid("this isn't base64!")),26<e?(e-=26,c.push(g^h>>>e),g=h<<32-e):(e+=6,g^=h<<32-e);e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.D();a?(this.r=a.r.slice(0),this.o=a.o.slice(0),this.h=a.h):this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
|
||||
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.r=this.N.slice(0);this.o=[];this.h=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.o=sjcl.bitArray.concat(this.o,a);b=this.h;a=this.h=b+sjcl.bitArray.bitLength(a);for(b=512+b&-512;b<=a;b+=512)z(this,c.splice(0,16));return this},finalize:function(){var a,b=this.o,c=this.r,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.h/
|
||||
4294967296));for(b.push(this.h|0);b.length;)z(this,b.splice(0,16));this.reset();return c},N:[],b:[],D:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}var b=0,c=2,d;a:for(;64>b;c++){for(d=2;d*d<=c;d++)if(0===c%d)continue a;8>b&&(this.N[b]=a(Math.pow(c,0.5)));this.b[b]=a(Math.pow(c,1/3));b++}}};
|
||||
function z(a,b){var c,d,e,f=b.slice(0),g=a.r,h=a.b,l=g[0],k=g[1],n=g[2],m=g[3],p=g[4],s=g[5],r=g[6],v=g[7];for(c=0;64>c;c++)16>c?d=f[c]:(d=f[c+1&15],e=f[c+14&15],d=f[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+f[c&15]+f[c+9&15]|0),d=d+v+(p>>>6^p>>>11^p>>>25^p<<26^p<<21^p<<7)+(r^p&(s^r))+h[c],v=r,r=s,s=p,p=m+d|0,m=n,n=k,k=l,l=d+(k&n^m&(k^n))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;g[0]=g[0]+l|0;g[1]=g[1]+k|0;g[2]=g[2]+n|0;g[3]=g[3]+m|0;g[4]=g[4]+p|0;g[5]=g[5]+s|0;g[6]=
|
||||
g[6]+r|0;g[7]=g[7]+v|0}
|
||||
sjcl.mode.ccm={name:"ccm",encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,l=h.bitLength(c)/8,k=h.bitLength(g)/8;e=e||64;d=d||[];7>l&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(f=2;4>f&&k>>>8*f;f++);f<15-l&&(f=15-l);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.K(a,b,c,d,e,f);g=sjcl.mode.ccm.n(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),l=f.clamp(b,h-e),k=f.bitSlice(b,
|
||||
h-e),h=(h-e)/8;7>g&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));l=sjcl.mode.ccm.n(a,l,c,k,e,b);a=sjcl.mode.ccm.K(a,l.data,c,d,e,b);f.equal(l.tag,a)||q(new sjcl.exception.corrupt("ccm: tag doesn't match"));return l.data},K:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,l=h.k;e/=8;(e%2||4>e||16<e)&&q(new sjcl.exception.invalid("ccm: invalid tag length"));(0xffffffff<d.length||0xffffffff<b.length)&&q(new sjcl.exception.bug("ccm: can't deal with 4GiB or more data"));
|
||||
f=[h.partial(8,(d.length?64:0)|e-2<<2|f-1)];f=h.concat(f,c);f[3]|=h.bitLength(b)/8;f=a.encrypt(f);if(d.length){c=h.bitLength(d)/8;65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c]));g=h.concat(g,d);for(d=0;d<g.length;d+=4)f=a.encrypt(l(f,g.slice(d,d+4).concat([0,0,0])))}for(d=0;d<b.length;d+=4)f=a.encrypt(l(f,b.slice(d,d+4).concat([0,0,0])));return h.clamp(f,8*e)},n:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.k;var l=b.length,k=h.bitLength(b);c=h.concat([h.partial(8,
|
||||
sjcl.mode.ccm={name:"ccm",encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,l=h.bitLength(c)/8,k=h.bitLength(g)/8;e=e||64;d=d||[];7>l&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(f=2;4>f&&k>>>8*f;f++);f<15-l&&(f=15-l);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.L(a,b,c,d,e,f);g=sjcl.mode.ccm.p(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),l=f.clamp(b,h-e),k=f.bitSlice(b,
|
||||
h-e),h=(h-e)/8;7>g&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));l=sjcl.mode.ccm.p(a,l,c,k,e,b);a=sjcl.mode.ccm.L(a,l.data,c,d,e,b);f.equal(l.tag,a)||q(new sjcl.exception.corrupt("ccm: tag doesn't match"));return l.data},L:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,l=h.l;e/=8;(e%2||4>e||16<e)&&q(new sjcl.exception.invalid("ccm: invalid tag length"));(0xffffffff<d.length||0xffffffff<b.length)&&q(new sjcl.exception.bug("ccm: can't deal with 4GiB or more data"));
|
||||
f=[h.partial(8,(d.length?64:0)|e-2<<2|f-1)];f=h.concat(f,c);f[3]|=h.bitLength(b)/8;f=a.encrypt(f);if(d.length){c=h.bitLength(d)/8;65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c]));g=h.concat(g,d);for(d=0;d<g.length;d+=4)f=a.encrypt(l(f,g.slice(d,d+4).concat([0,0,0])))}for(d=0;d<b.length;d+=4)f=a.encrypt(l(f,b.slice(d,d+4).concat([0,0,0])));return h.clamp(f,8*e)},p:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.l;var l=b.length,k=h.bitLength(b);c=h.concat([h.partial(8,
|
||||
f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!l)return{tag:d,data:[]};for(g=0;g<l;g+=4)c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,k)}}};
|
||||
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){128!==sjcl.bitArray.bitLength(c)&&q(new sjcl.exception.invalid("ocb iv must be 128 bits"));var g,h=sjcl.mode.ocb2.G,l=sjcl.bitArray,k=l.k,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=k(n,m),p=p.concat(k(c,a.encrypt(k(c,m)))),c=h(c);m=b.slice(g);b=l.bitLength(m);g=a.encrypt(k(c,[0,0,0,b]));m=l.clamp(k(m.concat([0,0,0]),g),b);n=k(n,k(m.concat([0,0,0]),g));n=a.encrypt(k(n,k(c,h(c))));d.length&&
|
||||
(n=k(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(l.concat(m,l.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){128!==sjcl.bitArray.bitLength(c)&&q(new sjcl.exception.invalid("ocb iv must be 128 bits"));e=e||64;var g=sjcl.mode.ocb2.G,h=sjcl.bitArray,l=h.k,k=[0,0,0,0],n=g(a.encrypt(c)),m,p,s=sjcl.bitArray.bitLength(b)-e,r=[];d=d||[];for(c=0;c+4<s/32;c+=4)m=l(n,a.decrypt(l(n,b.slice(c,c+4)))),k=l(k,m),r=r.concat(m),n=g(n);p=s-32*c;m=a.encrypt(l(n,[0,0,0,p]));m=l(m,h.clamp(b.slice(c),p).concat([0,0,0]));
|
||||
k=l(k,m);k=a.encrypt(l(k,l(n,g(n))));d.length&&(k=l(k,f?d:sjcl.mode.ocb2.pmac(a,d)));h.equal(h.clamp(k,e),h.bitSlice(b,s))||q(new sjcl.exception.corrupt("ocb: tag doesn't match"));return r.concat(h.clamp(m,p))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.G,e=sjcl.bitArray,f=e.k,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,
|
||||
d(h))),g))},G:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
|
||||
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.n(!0,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.n(u,a,f,d,c,e);g.equal(a.tag,b)||q(new sjcl.exception.corrupt("gcm: tag doesn't match"));return a.data},U:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.k;e=[0,0,0,0];f=b.slice(0);
|
||||
for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},f:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.U(b,a);return b},n:function(a,b,c,d,e,f){var g,h,l,k,n,m,p,s,r=sjcl.bitArray;m=c.length;p=r.bitLength(c);s=r.bitLength(d);h=r.bitLength(e);g=b.encrypt([0,
|
||||
0,0,0]);96===h?(e=e.slice(0),e=r.concat(e,[1])):(e=sjcl.mode.gcm.f(g,[0,0,0,0],e),e=sjcl.mode.gcm.f(g,e,[0,0,Math.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.f(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.f(g,h,c));for(k=0;k<m;k+=4)n[3]++,l=b.encrypt(n),c[k]^=l[0],c[k+1]^=l[1],c[k+2]^=l[2],c[k+3]^=l[3];c=r.clamp(c,p);a&&(d=sjcl.mode.gcm.f(g,h,c));a=[Math.floor(s/0x100000000),s&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.f(g,d,a);l=b.encrypt(e);d[0]^=l[0];
|
||||
d[1]^=l[1];d[2]^=l[2];d[3]^=l[3];return{tag:r.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.L=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.o=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.o[0].update(c[0]);this.o[1].update(c[1])};sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){a=(new this.L(this.o[0])).update(a).finalize();return(new this.L(this.o[1])).update(a).finalize()};
|
||||
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E3;(0>d||0>c)&&q(sjcl.exception.invalid("invalid params to pbkdf2"));"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,l,k=[],n=sjcl.bitArray;for(l=1;32*k.length<(d||1);l++){e=f=a.encrypt(n.concat(b,[l]));for(g=1;g<c;g++){f=a.encrypt(f);for(h=0;h<f.length;h++)e[h]^=f[h]}k=k.concat(e)}d&&(k=n.clamp(k,d));return k};
|
||||
sjcl.prng=function(a){this.b=[new sjcl.hash.sha256];this.h=[0];this.F=0;this.t={};this.C=0;this.J={};this.N=this.c=this.i=this.T=0;this.a=[0,0,0,0,0,0,0,0];this.e=[0,0,0,0];this.A=t;this.B=a;this.p=u;this.z={progress:{},seeded:{}};this.l=this.S=0;this.u=1;this.w=2;this.Q=0x10000;this.H=[0,48,64,96,128,192,0x100,384,512,768,1024];this.R=3E4;this.P=80};
|
||||
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;d===this.l&&q(new sjcl.exception.notReady("generator isn't seeded"));if(d&this.w){d=!(d&this.u);e=[];var f=0,g;this.N=e[0]=(new Date).valueOf()+this.R;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.b.length&&!(e=e.concat(this.b[g].finalize()),f+=this.h[g],this.h[g]=0,!d&&this.F&1<<g);g++);this.F>=1<<this.b.length&&(this.b.push(new sjcl.hash.sha256),this.h.push(0));this.c-=f;f>this.i&&(this.i=f);this.F++;
|
||||
this.a=sjcl.hash.sha256.hash(this.a.concat(e));this.A=new sjcl.cipher.aes(this.a);for(d=0;4>d&&!(this.e[d]=this.e[d]+1|0,this.e[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.Q&&A(this),e=B(this),c.push(e[0],e[1],e[2],e[3]);A(this);return c.slice(0,a)},setDefaultParanoia:function(a){this.B=a},addEntropy:function(a,b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.t[c],h=this.isReady(),l=0;d=this.J[c];d===t&&(d=this.J[c]=this.T++);g===t&&(g=this.t[c]=0);this.t[c]=(this.t[c]+1)%this.b.length;switch(typeof a){case "number":b===
|
||||
t&&(b=1);this.b[g].update([d,this.C++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else{"[object Array]"!==c&&(l=1);for(c=0;c<a.length&&!l;c++)"number"!=typeof a[c]&&(l=1)}if(!l){if(b===t)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e>>>=1;this.b[g].update([d,this.C++,2,b,f,a.length].concat(a))}break;case "string":b===t&&(b=a.length);this.b[g].update([d,this.C++,3,b,f,a.length]);this.b[g].update(a);
|
||||
break;default:l=1}l&&q(new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string"));this.h[g]+=b;this.c+=b;h===this.l&&(this.isReady()!==this.l&&C("seeded",Math.max(this.i,this.c)),C("progress",this.getProgress()))},isReady:function(a){a=this.H[a!==t?a:this.B];return this.i&&this.i>=a?this.h[0]>this.P&&(new Date).valueOf()>this.N?this.w|this.u:this.u:this.c>=a?this.w|this.l:this.l},getProgress:function(a){a=this.H[a?a:this.B];return this.i>=a?1:this.c>a?1:this.c/
|
||||
a},startCollectors:function(){this.p||(window.addEventListener?(window.addEventListener("load",this.r,u),window.addEventListener("mousemove",this.s,u)):document.attachEvent?(document.attachEvent("onload",this.r),document.attachEvent("onmousemove",this.s)):q(new sjcl.exception.bug("can't attach event")),this.p=!0)},stopCollectors:function(){this.p&&(window.removeEventListener?(window.removeEventListener("load",this.r,u),window.removeEventListener("mousemove",this.s,u)):window.detachEvent&&(window.detachEvent("onload",
|
||||
this.r),window.detachEvent("onmousemove",this.s)),this.p=u)},addEventListener:function(a,b){this.z[a][this.S++]=b},removeEventListener:function(a,b){var c,d,e=this.z[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},s:function(a){sjcl.random.addEntropy([a.x||a.clientX||a.offsetX||0,a.y||a.clientY||a.offsetY||0],2,"mouse")},r:function(){sjcl.random.addEntropy((new Date).valueOf(),2,"loadtime")}};
|
||||
function C(a,b){var c,d=sjcl.random.z[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c](b)}function A(a){a.a=B(a).concat(B(a));a.A=new sjcl.cipher.aes(a.a)}function B(a){for(var b=0;4>b&&!(a.e[b]=a.e[b]+1|0,a.e[b]);b++);return a.A.encrypt(a.e)}sjcl.random=new sjcl.prng(6);try{var D=new Uint32Array(32);crypto.getRandomValues(D);sjcl.random.addEntropy(D,1024,"crypto['getRandomValues']")}catch(E){}
|
||||
sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},encrypt:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.d({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.d(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
|
||||
4<f.iv.length)&&q(new sjcl.exception.invalid("json encrypt: invalid parameters"));"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.d(d,f);d.key=a;f.ct=sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return e.encode(f)},
|
||||
decrypt:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.d(e.d(e.d({},e.defaults),e.decode(b)),c,!0);var f;c=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"===typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)&&q(new sjcl.exception.invalid("json decrypt: invalid parameters"));
|
||||
"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,b),a=f.key.slice(0,b.ks/32),b.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof c&&(c=sjcl.codec.utf8String.toBits(c));f=new sjcl.cipher[b.cipher](a);c=sjcl.mode[b.mode].decrypt(f,b.ct,b.iv,c,b.ts);e.d(d,b);d.key=a;return sjcl.codec.utf8String.fromBits(c)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b))switch(b.match(/^[a-z0-9]+$/i)||
|
||||
q(new sjcl.exception.invalid("json encode: invalid property name")),c+=d+'"'+b+'":',d=",",typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:q(new sjcl.exception.bug("json encode: unsupported type"))}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");a.match(/^\{.*\}$/)||q(new sjcl.exception.invalid("json decode: this isn't json!"));a=a.replace(/^\{|\}$/g,"").split(/,/);var b=
|
||||
{},c,d;for(c=0;c<a.length;c++)(d=a[c].match(/^(?:(["']?)([a-z][a-z0-9]*)\1):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i))||q(new sjcl.exception.invalid("json decode: this isn't json!")),b[d[2]]=d[3]?parseInt(d[3],10):d[2].match(/^(ct|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape(d[4]);return b},d:function(a,b,c){a===t&&(a={});if(b===t)return a;for(var d in b)b.hasOwnProperty(d)&&(c&&(a[d]!==t&&a[d]!==b[d])&&q(new sjcl.exception.invalid("required parameter overridden")),a[d]=b[d]);return a},X:function(a,
|
||||
b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c},W:function(a,b){var c={},d;for(d=0;d<b.length;d++)a[b[d]]!==t&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.V={};
|
||||
sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.V,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=b.salt===t?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
|
||||
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){128!==sjcl.bitArray.bitLength(c)&&q(new sjcl.exception.invalid("ocb iv must be 128 bits"));var g,h=sjcl.mode.ocb2.H,l=sjcl.bitArray,k=l.l,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=k(n,m),p=p.concat(k(c,a.encrypt(k(c,m)))),c=h(c);m=b.slice(g);b=l.bitLength(m);g=a.encrypt(k(c,[0,0,0,b]));m=l.clamp(k(m.concat([0,0,0]),g),b);n=k(n,k(m.concat([0,0,0]),g));n=a.encrypt(k(n,k(c,h(c))));d.length&&
|
||||
(n=k(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(l.concat(m,l.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){128!==sjcl.bitArray.bitLength(c)&&q(new sjcl.exception.invalid("ocb iv must be 128 bits"));e=e||64;var g=sjcl.mode.ocb2.H,h=sjcl.bitArray,l=h.l,k=[0,0,0,0],n=g(a.encrypt(c)),m,p,s=sjcl.bitArray.bitLength(b)-e,r=[];d=d||[];for(c=0;c+4<s/32;c+=4)m=l(n,a.decrypt(l(n,b.slice(c,c+4)))),k=l(k,m),r=r.concat(m),n=g(n);p=s-32*c;m=a.encrypt(l(n,[0,0,0,p]));m=l(m,h.clamp(b.slice(c),p).concat([0,0,0]));
|
||||
k=l(k,m);k=a.encrypt(l(k,l(n,g(n))));d.length&&(k=l(k,f?d:sjcl.mode.ocb2.pmac(a,d)));h.equal(h.clamp(k,e),h.bitSlice(b,s))||q(new sjcl.exception.corrupt("ocb: tag doesn't match"));return r.concat(h.clamp(m,p))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.H,e=sjcl.bitArray,f=e.l,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,
|
||||
d(h))),g))},H:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
|
||||
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.p(!0,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.p(u,a,f,d,c,e);g.equal(a.tag,b)||q(new sjcl.exception.corrupt("gcm: tag doesn't match"));return a.data},Z:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.l;e=[0,0,0,0];f=b.slice(0);
|
||||
for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},g:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.Z(b,a);return b},p:function(a,b,c,d,e,f){var g,h,l,k,n,m,p,s,r=sjcl.bitArray;m=c.length;p=r.bitLength(c);s=r.bitLength(d);h=r.bitLength(e);g=b.encrypt([0,
|
||||
0,0,0]);96===h?(e=e.slice(0),e=r.concat(e,[1])):(e=sjcl.mode.gcm.g(g,[0,0,0,0],e),e=sjcl.mode.gcm.g(g,e,[0,0,Math.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.g(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.g(g,h,c));for(k=0;k<m;k+=4)n[3]++,l=b.encrypt(n),c[k]^=l[0],c[k+1]^=l[1],c[k+2]^=l[2],c[k+3]^=l[3];c=r.clamp(c,p);a&&(d=sjcl.mode.gcm.g(g,h,c));a=[Math.floor(s/0x100000000),s&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.g(g,d,a);l=b.encrypt(e);d[0]^=l[0];
|
||||
d[1]^=l[1];d[2]^=l[2];d[3]^=l[3];return{tag:r.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.M=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.n=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.n[0].update(c[0]);this.n[1].update(c[1]);this.G=new b(this.n[0])};
|
||||
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){this.Q&&q(new sjcl.exception.invalid("encrypt on already updated hmac called!"));this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.G=new this.M(this.n[0]);this.Q=u};sjcl.misc.hmac.prototype.update=function(a){this.Q=!0;this.G.update(a)};sjcl.misc.hmac.prototype.digest=function(){var a=this.G.finalize(),a=(new this.M(this.n[1])).update(a).finalize();this.reset();return a};
|
||||
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E3;(0>d||0>c)&&q(sjcl.exception.invalid("invalid params to pbkdf2"));"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,l,k=[],n=sjcl.bitArray;for(l=1;32*k.length<(d||1);l++){e=f=a.encrypt(n.concat(b,[l]));for(g=1;g<c;g++){f=a.encrypt(f);for(h=0;h<f.length;h++)e[h]^=f[h]}k=k.concat(e)}d&&(k=n.clamp(k,d));return k};
|
||||
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.i=[0];this.F=0;this.s={};this.C=0;this.K={};this.O=this.d=this.j=this.W=0;this.b=[0,0,0,0,0,0,0,0];this.f=[0,0,0,0];this.A=t;this.B=a;this.q=u;this.w={progress:{},seeded:{}};this.m=this.V=0;this.t=1;this.u=2;this.S=0x10000;this.I=[0,48,64,96,128,192,0x100,384,512,768,1024];this.T=3E4;this.R=80};
|
||||
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;d===this.m&&q(new sjcl.exception.notReady("generator isn't seeded"));if(d&this.u){d=!(d&this.t);e=[];var f=0,g;this.O=e[0]=(new Date).valueOf()+this.T;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&!(e=e.concat(this.c[g].finalize()),f+=this.i[g],this.i[g]=0,!d&&this.F&1<<g);g++);this.F>=1<<this.c.length&&(this.c.push(new sjcl.hash.sha256),this.i.push(0));this.d-=f;f>this.j&&(this.j=f);this.F++;
|
||||
this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.A=new sjcl.cipher.aes(this.b);for(d=0;4>d&&!(this.f[d]=this.f[d]+1|0,this.f[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.S&&A(this),e=B(this),c.push(e[0],e[1],e[2],e[3]);A(this);return c.slice(0,a)},setDefaultParanoia:function(a,b){0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b&&q("Setting paranoia=0 will ruin your security; use it only for testing");this.B=a},addEntropy:function(a,b,c){c=c||"user";var d,e,f=(new Date).valueOf(),
|
||||
g=this.s[c],h=this.isReady(),l=0;d=this.K[c];d===t&&(d=this.K[c]=this.W++);g===t&&(g=this.s[c]=0);this.s[c]=(this.s[c]+1)%this.c.length;switch(typeof a){case "number":b===t&&(b=1);this.c[g].update([d,this.C++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else{"[object Array]"!==c&&(l=1);for(c=0;c<a.length&&!l;c++)"number"!==typeof a[c]&&(l=1)}if(!l){if(b===t)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,
|
||||
e>>>=1;this.c[g].update([d,this.C++,2,b,f,a.length].concat(a))}break;case "string":b===t&&(b=a.length);this.c[g].update([d,this.C++,3,b,f,a.length]);this.c[g].update(a);break;default:l=1}l&&q(new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string"));this.i[g]+=b;this.d+=b;h===this.m&&(this.isReady()!==this.m&&C("seeded",Math.max(this.j,this.d)),C("progress",this.getProgress()))},isReady:function(a){a=this.I[a!==t?a:this.B];return this.j&&this.j>=a?this.i[0]>this.R&&
|
||||
(new Date).valueOf()>this.O?this.u|this.t:this.t:this.d>=a?this.u|this.m:this.m},getProgress:function(a){a=this.I[a?a:this.B];return this.j>=a?1:this.d>a?1:this.d/a},startCollectors:function(){this.q||(this.a={loadTimeCollector:D(this,this.aa),mouseCollector:D(this,this.ba),keyboardCollector:D(this,this.$),accelerometerCollector:D(this,this.U)},window.addEventListener?(window.addEventListener("load",this.a.loadTimeCollector,u),window.addEventListener("mousemove",this.a.mouseCollector,u),window.addEventListener("keypress",
|
||||
this.a.keyboardCollector,u),window.addEventListener("devicemotion",this.a.accelerometerCollector,u)):document.attachEvent?(document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector)):q(new sjcl.exception.bug("can't attach event")),this.q=!0)},stopCollectors:function(){this.q&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,u),window.removeEventListener("mousemove",
|
||||
this.a.mouseCollector,u),window.removeEventListener("keypress",this.a.keyboardCollector,u),window.removeEventListener("devicemotion",this.a.accelerometerCollector,u)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.q=u)},addEventListener:function(a,b){this.w[a][this.V++]=b},removeEventListener:function(a,b){var c,d,e=this.w[a],f=[];for(d in e)e.hasOwnProperty(d)&&
|
||||
e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},$:function(){E(1)},ba:function(a){var b,c;try{b=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&sjcl.random.addEntropy([b,c],2,"mouse");E(0)},aa:function(){E(2)},U:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&sjcl.random.addEntropy(b,1,"accelerometer")}a&&sjcl.random.addEntropy(a,
|
||||
2,"accelerometer");E(0)}};function C(a,b){var c,d=sjcl.random.w[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c](b)}function E(a){"undefined"!==typeof window&&window.performance&&"function"===typeof window.performance.now?sjcl.random.addEntropy(window.performance.now(),a,"loadtime"):sjcl.random.addEntropy((new Date).valueOf(),a,"loadtime")}function A(a){a.b=B(a).concat(B(a));a.A=new sjcl.cipher.aes(a.b)}
|
||||
function B(a){for(var b=0;4>b&&!(a.f[b]=a.f[b]+1|0,a.f[b]);b++);return a.A.encrypt(a.f)}function D(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
|
||||
a:try{var F,G,H,I;if(I="undefined"!==typeof module){var J;if(J=module.exports){var K;try{K=require("crypto")}catch(L){K=null}J=(G=K)&&G.randomBytes}I=J}if(I)F=G.randomBytes(128),F=new Uint32Array((new Uint8Array(F)).buffer),sjcl.random.addEntropy(F,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){H=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(H);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(H);
|
||||
else break a;sjcl.random.addEntropy(H,1024,"crypto['getRandomValues']")}}catch(M){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(M))}
|
||||
sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},Y:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.e({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.e(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||4<
|
||||
f.iv.length)&&q(new sjcl.exception.invalid("json encrypt: invalid parameters"));"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.e(d,f);d.key=a;f.ct=sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt:function(a,
|
||||
b,c,d){var e=sjcl.json,f=e.Y.apply(e,arguments);return e.encode(f)},X:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.e(e.e(e.e({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"===typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)&&q(new sjcl.exception.invalid("json decrypt: invalid parameters"));
|
||||
"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f=sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.e(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.X(a,e.decode(b),c,d)},encode:function(a){var b,
|
||||
c="{",d="";for(b in a)if(a.hasOwnProperty(b))switch(b.match(/^[a-z0-9]+$/i)||q(new sjcl.exception.invalid("json encode: invalid property name")),c+=d+'"'+b+'":',d=",",typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:q(new sjcl.exception.bug("json encode: unsupported type"))}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");a.match(/^\{.*\}$/)||q(new sjcl.exception.invalid("json decode: this isn't json!"));
|
||||
a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++)(d=a[c].match(/^(?:(["']?)([a-z][a-z0-9]*)\1):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i))||q(new sjcl.exception.invalid("json decode: this isn't json!")),b[d[2]]=d[3]?parseInt(d[3],10):d[2].match(/^(ct|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape(d[4]);return b},e:function(a,b,c){a===t&&(a={});if(b===t)return a;for(var d in b)b.hasOwnProperty(d)&&(c&&(a[d]!==t&&a[d]!==b[d])&&q(new sjcl.exception.invalid("required parameter overridden")),
|
||||
a[d]=b[d]);return a},ea:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c},da:function(a,b){var c={},d;for(d=0;d<b.length;d++)a[b[d]]!==t&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.ca={};
|
||||
sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.ca,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=b.salt===t?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
|
||||
|
||||
115
src/js/sjcl/test/bitArray_test.js
Normal file
115
src/js/sjcl/test/bitArray_test.js
Normal file
@@ -0,0 +1,115 @@
|
||||
(function() {
|
||||
|
||||
function word2hex(w) {
|
||||
return "0x" + ((w|0)+0xF00000000000).toString(16).substr(4);
|
||||
}
|
||||
|
||||
var b0 = sjcl.bitArray.partial(1, 0);
|
||||
var b1 = sjcl.bitArray.partial(1, 1);
|
||||
|
||||
function concatbits(s) {
|
||||
var j, b, a = [];
|
||||
for (j = 0; j < s.length; ++j) {
|
||||
b = (s[j] == '1' ? b1 : b0);
|
||||
a = sjcl.bitArray.concat(a, [b]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
new sjcl.test.TestCase("bitArray single bits", function (cb) {
|
||||
if (!sjcl.bitArray) {
|
||||
this.unimplemented();
|
||||
cb && cb();
|
||||
return;
|
||||
}
|
||||
|
||||
this.require((b0|0) === (0x00000000|0), "bitstring '0': " + word2hex(b0));
|
||||
this.require((b1|0) === (0x80000000|0), "bitstring '1': " + word2hex(b1));
|
||||
|
||||
cb && cb();
|
||||
});
|
||||
|
||||
new sjcl.test.TestCase("bitArray concat small bitstrings", function (cb) {
|
||||
if (!sjcl.bitArray) {
|
||||
this.unimplemented();
|
||||
cb && cb();
|
||||
return;
|
||||
}
|
||||
|
||||
var i, kat = sjcl.test.vector.bitArray.bits, tv, a, b, bitlen, t;
|
||||
for (i=0; i<kat.length; i++) {
|
||||
tv = kat[i];
|
||||
a = concatbits(tv[0]);
|
||||
bitlen = sjcl.bitArray.bitLength(a);
|
||||
t = "bitstring '" + tv[0] + "': ";
|
||||
this.require(1 === a.length, t + "array length is 1: " + a.length);
|
||||
this.require(bitlen === tv[0].length, t + "length " + bitlen + " matches input length " + tv[0].length);
|
||||
b = sjcl.bitArray.partial(tv[0].length, tv[1]);
|
||||
this.require(a[0] === b, t + "array matches shifted number: " + word2hex(a[0]) + " == " + word2hex(b));
|
||||
b = 0 | (a[0] >>> (32 - tv[0].length)); // unsigned shift, convert to signed word
|
||||
this.require(b === (tv[1]|0), t + "array entry shifted is number: " + word2hex(b) + " == " + word2hex(tv[1]));
|
||||
}
|
||||
|
||||
cb && cb();
|
||||
});
|
||||
|
||||
|
||||
new sjcl.test.TestCase("bitArray concat, slicing, shifting and clamping", function (cb) {
|
||||
if (!sjcl.bitArray) {
|
||||
this.unimplemented();
|
||||
cb && cb();
|
||||
return;
|
||||
}
|
||||
|
||||
var i, j, kat = sjcl.test.vector.bitArray.slices, tv, a, a1, b, bitlen, t;
|
||||
for (i=0; i<kat.length; i++) {
|
||||
tv = kat[i];
|
||||
a = [];
|
||||
b = [];
|
||||
|
||||
bitlen = 0;
|
||||
for (j=0; j<tv[0].length; j++) {
|
||||
b[j] = concatbits(tv[0][j]);
|
||||
a = sjcl.bitArray.concat(a, b[j]);
|
||||
bitlen += tv[0][j].length;
|
||||
}
|
||||
|
||||
// shift last array entry and set partial length on it
|
||||
a1 = tv[1]; a1 = a1.slice(0, a1.length);
|
||||
bitlen &= 31;
|
||||
if (0 !== bitlen) a1[a1.length-1] = sjcl.bitArray.partial(bitlen, a1[a1.length-1]);
|
||||
|
||||
this.require(sjcl.bitArray.equal(a, a1), "concat: [" + a + "] == [" + a1 + "]");
|
||||
|
||||
t = 0;
|
||||
for (j=0; j<tv[0].length; j++) {
|
||||
bitlen = sjcl.bitArray.bitLength(b[j]);
|
||||
this.require(bitlen === tv[0][j].length, "bitstring length");
|
||||
a1 = sjcl.bitArray.bitSlice(a, t, t + bitlen);
|
||||
this.require(sjcl.bitArray.equal(b[j], a1), "slice after concat: [" + b[j] + "] == [" + a1 + "]");
|
||||
t += bitlen;
|
||||
}
|
||||
}
|
||||
|
||||
cb && cb();
|
||||
});
|
||||
|
||||
new sjcl.test.TestCase("bitArray byteswap", function (cb) {
|
||||
if (!sjcl.bitArray) {
|
||||
this.unimplemented();
|
||||
cb && cb();
|
||||
return;
|
||||
}
|
||||
|
||||
var i, kat = sjcl.test.vector.bitArray.byteswap, tv, a;
|
||||
for (i=0; i<kat.length; i++) {
|
||||
tv = kat[i];
|
||||
|
||||
a = tv[1];
|
||||
this.require(sjcl.bitArray.equal(tv[0], sjcl.bitArray.byteswapM(a.slice(0, a.length))));
|
||||
}
|
||||
|
||||
cb && cb();
|
||||
});
|
||||
|
||||
})();
|
||||
163
src/js/sjcl/test/bitArray_vectors.js
Normal file
163
src/js/sjcl/test/bitArray_vectors.js
Normal file
@@ -0,0 +1,163 @@
|
||||
sjcl.test.vector.bitArray = {};
|
||||
|
||||
// random test cases generated with ruby String#to_i(radix) and Fixnum#to_s(radix)
|
||||
|
||||
// bitstrings (<= 32 bits) encoding a number
|
||||
sjcl.test.vector.bitArray.bits = [
|
||||
[ "00" , 0|0x0 ],
|
||||
[ "01" , 0|0x1 ],
|
||||
[ "10" , 0|0x2 ],
|
||||
[ "11" , 0|0x3 ],
|
||||
[ "000" , 0|0x0 ],
|
||||
[ "011" , 0|0x3 ],
|
||||
[ "101" , 0|0x5 ],
|
||||
[ "110" , 0|0x6 ],
|
||||
[ "0100" , 0|0x4 ],
|
||||
[ "0101" , 0|0x5 ],
|
||||
[ "1000" , 0|0x8 ],
|
||||
[ "1100" , 0|0xc ],
|
||||
[ "00101" , 0|0x5 ],
|
||||
[ "01010" , 0|0xa ],
|
||||
[ "10011" , 0|0x13 ],
|
||||
[ "11010" , 0|0x1a ],
|
||||
[ "001100" , 0|0xc ],
|
||||
[ "001110" , 0|0xe ],
|
||||
[ "010100" , 0|0x14 ],
|
||||
[ "100111" , 0|0x27 ],
|
||||
[ "0001011" , 0|0xb ],
|
||||
[ "0001101" , 0|0xd ],
|
||||
[ "1000100" , 0|0x44 ],
|
||||
[ "1101011" , 0|0x6b ],
|
||||
[ "00100001" , 0|0x21 ],
|
||||
[ "00100111" , 0|0x27 ],
|
||||
[ "00101000" , 0|0x28 ],
|
||||
[ "10101111" , 0|0xaf ],
|
||||
[ "000100000" , 0|0x20 ],
|
||||
[ "100100011" , 0|0x123 ],
|
||||
[ "100111001" , 0|0x139 ],
|
||||
[ "111010011" , 0|0x1d3 ],
|
||||
[ "0001001011" , 0|0x4b ],
|
||||
[ "0001100110" , 0|0x66 ],
|
||||
[ "0010110111" , 0|0xb7 ],
|
||||
[ "1011101111" , 0|0x2ef ],
|
||||
[ "01000010110" , 0|0x216 ],
|
||||
[ "01001101000" , 0|0x268 ],
|
||||
[ "10111101001" , 0|0x5e9 ],
|
||||
[ "11111100000" , 0|0x7e0 ],
|
||||
[ "000101010001" , 0|0x151 ],
|
||||
[ "010101111111" , 0|0x57f ],
|
||||
[ "101010001110" , 0|0xa8e ],
|
||||
[ "110101100010" , 0|0xd62 ],
|
||||
[ "0010001111010" , 0|0x47a ],
|
||||
[ "1000000001100" , 0|0x100c ],
|
||||
[ "1100011000000" , 0|0x18c0 ],
|
||||
[ "1110011000011" , 0|0x1cc3 ],
|
||||
[ "00111101111110" , 0|0xf7e ],
|
||||
[ "01101011001001" , 0|0x1ac9 ],
|
||||
[ "10111000111101" , 0|0x2e3d ],
|
||||
[ "11101010011110" , 0|0x3a9e ],
|
||||
[ "010111101010110" , 0|0x2f56 ],
|
||||
[ "100011010110000" , 0|0x46b0 ],
|
||||
[ "110001001100100" , 0|0x6264 ],
|
||||
[ "111011000100110" , 0|0x7626 ],
|
||||
[ "0100101111001100" , 0|0x4bcc ],
|
||||
[ "1000000001101100" , 0|0x806c ],
|
||||
[ "1001000100110110" , 0|0x9136 ],
|
||||
[ "1101010000100011" , 0|0xd423 ],
|
||||
[ "01001001001101110" , 0|0x926e ],
|
||||
[ "01111001111000010" , 0|0xf3c2 ],
|
||||
[ "10011011011000011" , 0|0x136c3 ],
|
||||
[ "10101011001110000" , 0|0x15670 ],
|
||||
[ "010000000101000110" , 0|0x10146 ],
|
||||
[ "011000100101110001" , 0|0x18971 ],
|
||||
[ "101100100110110111" , 0|0x2c9b7 ],
|
||||
[ "101110100100101111" , 0|0x2e92f ],
|
||||
[ "0010101100101000000" , 0|0x15940 ],
|
||||
[ "1011010010000101010" , 0|0x5a42a ],
|
||||
[ "1011100111011011000" , 0|0x5ced8 ],
|
||||
[ "1111011110011111110" , 0|0x7bcfe ],
|
||||
[ "00101000011011111111" , 0|0x286ff ],
|
||||
[ "01111001100011000100" , 0|0x798c4 ],
|
||||
[ "11111001001110101011" , 0|0xf93ab ],
|
||||
[ "11111001111001101001" , 0|0xf9e69 ],
|
||||
[ "000110100000110010101" , 0|0x34195 ],
|
||||
[ "011110000101101101111" , 0|0xf0b6f ],
|
||||
[ "101111010011001100110" , 0|0x17a666 ],
|
||||
[ "111101001011110010001" , 0|0x1e9791 ],
|
||||
[ "1001111100011011100001" , 0|0x27c6e1 ],
|
||||
[ "1011110101000101010110" , 0|0x2f5156 ],
|
||||
[ "1100000100011110001011" , 0|0x30478b ],
|
||||
[ "1100001010010110111111" , 0|0x30a5bf ],
|
||||
[ "01001111001101000111101" , 0|0x279a3d ],
|
||||
[ "10110011101111110000001" , 0|0x59df81 ],
|
||||
[ "11000001101100110100011" , 0|0x60d9a3 ],
|
||||
[ "11011000010110110010110" , 0|0x6c2d96 ],
|
||||
[ "010011110100100110010100" , 0|0x4f4994 ],
|
||||
[ "011101110001100111111110" , 0|0x7719fe ],
|
||||
[ "011110001010011011100011" , 0|0x78a6e3 ],
|
||||
[ "111100010001011101111110" , 0|0xf1177e ],
|
||||
[ "0010110000010110001000010" , 0|0x582c42 ],
|
||||
[ "0100100011001001101110000" , 0|0x919370 ],
|
||||
[ "1000111001010110111010110" , 0|0x11cadd6 ],
|
||||
[ "1111001100101000010010101" , 0|0x1e65095 ],
|
||||
[ "00110010011100010101111111" , 0|0xc9c57f ],
|
||||
[ "00111101011011010100111110" , 0|0xf5b53e ],
|
||||
[ "01100000111011111010011100" , 0|0x183be9c ],
|
||||
[ "11010001100110101111010111" , 0|0x3466bd7 ],
|
||||
[ "010000001111100110000110011" , 0|0x207cc33 ],
|
||||
[ "011010010000110000101011111" , 0|0x348615f ],
|
||||
[ "011010110001110110001110010" , 0|0x358ec72 ],
|
||||
[ "110110100001001001001110000" , 0|0x6d09270 ],
|
||||
[ "0101000000000001000011100101" , 0|0x50010e5 ],
|
||||
[ "0110011001001100011111111100" , 0|0x664c7fc ],
|
||||
[ "1001011010000001100110111101" , 0|0x96819bd ],
|
||||
[ "1011011101000000111000000010" , 0|0xb740e02 ],
|
||||
[ "00100111111011011111010101101" , 0|0x4fdbead ],
|
||||
[ "00110000011001110110101110010" , 0|0x60ced72 ],
|
||||
[ "10111110111000010010010111101" , 0|0x17dc24bd ],
|
||||
[ "11010001000001110010101000010" , 0|0x1a20e542 ],
|
||||
[ "001001010001010111111101010111" , 0|0x9457f57 ],
|
||||
[ "100110011101100000110111111010" , 0|0x26760dfa ],
|
||||
[ "100111000100011001010011111011" , 0|0x271194fb ],
|
||||
[ "111011110110101110110111010101" , 0|0x3bdaedd5 ],
|
||||
[ "0111100111010100101010000111100" , 0|0x3cea543c ],
|
||||
[ "1000010011010100111001110000100" , 0|0x426a7384 ],
|
||||
[ "1001110000000100001011010001010" , 0|0x4e02168a ],
|
||||
[ "1101000000000110110010011010100" , 0|0x680364d4 ],
|
||||
[ "00000011100100001011101011100111", 0|0x390bae7 ],
|
||||
[ "10011110110111111000010010010011", 0|0x9edf8493 ],
|
||||
[ "11000101100000110001011010111100", 0|0xc58316bc ],
|
||||
[ "11111010101110011001010001011000", 0|0xfab99458 ]
|
||||
];
|
||||
|
||||
// concat some bitstrings into an array (the last array entry here is not "high" shifted yet)
|
||||
sjcl.test.vector.bitArray.slices = [
|
||||
// lengths: 17, 16, 15, 14, 13
|
||||
[ ["00100010111010110", "0010000111100001", "101111111100010", "10111011110000", "1100100100001" ], [0|0x22eb10f0, 0|0xdfe2bbc3, 0|0x121] ],
|
||||
[ ["00001010100110010", "0000100011110001", "111110101100100", "10110111000101", "0000100111011" ], [0|0x0a990478, 0|0xfd64b714, 0|0x13b] ],
|
||||
[ ["10110101101100001", "0000110110010100", "110100011010100", "01011010010111", "0101101011011" ], [0|0xb5b086ca, 0|0x68d45a5d, 0|0x35b] ],
|
||||
[ ["01010010001010110", "1110010000100111", "001010110101110", "10110111101000", "0100000010100" ], [0|0x522b7213, 0|0x95aeb7a1, 0|0x014] ],
|
||||
[ ["10011001001100110", "0100100011100010", "000110011001001", "00101101101000", "0001111101100" ], [0|0x99332471, 0|0x0cc92da0, 0|0x3ec] ],
|
||||
[ ["01111100000110000", "1000101001000010", "110101001111111", "01001010110110", "0111100000001" ], [0|0x7c184521, 0|0x6a7f4ad9, 0|0x701] ],
|
||||
[ ["00110011010100110", "0100101101110000", "110101110100100", "00111010010110", "0110011011100" ], [0|0x335325b8, 0|0x6ba43a59, 0|0x4dc] ],
|
||||
[ ["11111110011100100", "1111101001010011", "001000100110010", "01101101100001", "0001011101011" ], [0|0xfe727d29, 0|0x91326d84, 0|0x2eb] ],
|
||||
[ ["00100011001001000", "1001010100000100", "010111001100111", "11011111000000", "0100111101110" ], [0|0x23244a82, 0|0x2e67df01, 0|0x1ee] ],
|
||||
[ ["10111111100000010", "0111110011010001", "001000101001110", "11101010011001", "0101111101110" ], [0|0xbf813e68, 0|0x914eea65, 0|0x3ee] ],
|
||||
// lengths: 17, 15, 32, 10, 20
|
||||
[ ["00001111000110001", "110100011111001", "10010110001110010011011000011111", "1001101101", "01110010001111001110" ], [0|0x0f18e8f9, 0|0x9639361f, 0|0x26d723ce] ],
|
||||
[ ["11011111010101100", "101010100101100", "11101101011001011011010111101011", "0010110010", "11110011110110000010" ], [0|0xdf56552c, 0|0xed65b5eb, 0|0x0b2f3d82] ],
|
||||
[ ["10100100001000101", "100111001100011", "00111100101000110010000011101001", "1001110001", "11000000001111111110" ], [0|0xa422ce63, 0|0x3ca320e9, 0|0x271c03fe] ],
|
||||
[ ["01110001111111010", "000101001101110", "00001100011010100100001011111001", "1011111010", "00011001110111111001" ], [0|0x71fd0a6e, 0|0x0c6a42f9, 0|0x2fa19df9] ],
|
||||
[ ["01001100010011001", "000111011000100", "10100000110101110110011110001100", "0011000001", "11001101010101011100" ], [0|0x4c4c8ec4, 0|0xa0d7678c, 0|0x0c1cd55c] ],
|
||||
[ ["01010010100110110", "110111110001000", "10011100001100010100000110000000", "1100111101", "00010001110100111101" ], [0|0x529b6f88, 0|0x9c314180, 0|0x33d11d3d] ],
|
||||
[ ["11010100011101101", "110101011011010", "01000110000011001111101110100001", "0001001110", "01001100010010001010" ], [0|0xd476eada, 0|0x460cfba1, 0|0x04e4c48a] ],
|
||||
[ ["11000001010001101", "001111011110111", "10000010100111010111011000100001", "0011000011", "11011110110000101000" ], [0|0xc1469ef7, 0|0x829d7621, 0|0x0c3dec28] ],
|
||||
[ ["11000101100010100", "000110111111110", "11111011110010001100001100010000", "0000101010", "10000011010011100011" ], [0|0xc58a0dfe, 0|0xfbc8c310, 0|0x02a834e3] ],
|
||||
[ ["11111111110100101", "110101000011001", "10101010010100111010100010110100", "0010011000", "10100110001000000010" ], [0|0xffd2ea19, 0|0xaa53a8b4, 0|0x098a6202] ]
|
||||
];
|
||||
|
||||
sjcl.test.vector.bitArray.byteswap = [
|
||||
[ [ 0xdab1a44e, 0x73fdc3de, 0xed6e6f00, 0x5d221b85, 0xadb987a4, 0xc20eda76, 0xa0d40d0c, 0xd1da9657, 0xd85eebf0, 0xd3f9c06d, 0xca1e39b0, 0xccd7eaeb, 0xb1dd6bd0, 0x7315a9e6, 0x77cfcac4, 0xf7914c19, 0x1bc15354, 0x935afabc, 0x3ee9d375, 0xd18a095f]
|
||||
, [ 0x4ea4b1da, 0xdec3fd73, 0x006f6eed, 0x851b225d, 0xa487b9ad, 0x76da0ec2, 0x0c0dd4a0, 0x5796dad1, 0xf0eb5ed8, 0x6dc0f9d3, 0xb0391eca, 0xebead7cc, 0xd06bddb1, 0xe6a91573, 0xc4cacf77, 0x194c91f7, 0x5453c11b, 0xbcfa5a93, 0x75d3e93e, 0x5f098ad1]
|
||||
]
|
||||
];
|
||||
@@ -7,7 +7,7 @@ new sjcl.test.TestCase("ECC convenience test", function (cb) {
|
||||
|
||||
try {
|
||||
var keys = sjcl.ecc.elGamal.generateKeys(192,0);
|
||||
|
||||
|
||||
var ciphertext = sjcl.encrypt(keys.pub, "hello world");
|
||||
var plaintext = sjcl.decrypt(keys.sec, ciphertext);
|
||||
|
||||
|
||||
@@ -5,11 +5,23 @@ new sjcl.test.TestCase("HMAC official test vectors", function (cb) {
|
||||
return;
|
||||
}
|
||||
|
||||
var i, kat = sjcl.test.vector.hmac, tv, h=sjcl.codec.hex, out;
|
||||
var i, kat = sjcl.test.vector.hmac, tv, h=sjcl.codec.hex, out, data, mac;
|
||||
for (i=0; i<kat.length; i++) {
|
||||
tv = kat[i];
|
||||
out = h.fromBits((new sjcl.misc.hmac(h.toBits(tv.key))).mac(h.toBits(tv.data)));
|
||||
data = h.toBits(tv.data);
|
||||
mac = new sjcl.misc.hmac(h.toBits(tv.key));
|
||||
|
||||
out = h.fromBits(mac.mac(data));
|
||||
this.require (out.substr(0,tv.mac.length) == tv.mac, "hmac #"+i);
|
||||
|
||||
out = h.fromBits(mac.mac(data));
|
||||
this.require (out.substr(0,tv.mac.length) == tv.mac, "hmac reset #"+i);
|
||||
|
||||
mac.update(sjcl.bitArray.bitSlice(data, 0, sjcl.bitArray.bitLength(data)/2));
|
||||
mac.update(sjcl.bitArray.bitSlice(data, sjcl.bitArray.bitLength(data)/2));
|
||||
|
||||
out = h.fromBits(mac.digest());
|
||||
this.require (out.substr(0,tv.mac.length) == tv.mac, "hmac reset #"+i);
|
||||
}
|
||||
cb && cb();
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Official HMAC test vectors. */
|
||||
//Nilos: http://tools.ietf.org/html/draft-nystrom-smime-hmac-sha-02 for
|
||||
sjcl.test.vector.hmac = [
|
||||
{ key: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
||||
data: "4869205468657265",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user