mirror of
https://github.com/Xahau/xahau.js.git
synced 2025-11-04 21:15:47 +00:00
Compare commits
370 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b47d7d91 | ||
|
|
a93c580c92 | ||
|
|
030e2786d1 | ||
|
|
56bbe1d437 | ||
|
|
1fff5ea6dc | ||
|
|
ad9956375f | ||
|
|
7d7970d318 | ||
|
|
f4fa10b9c0 | ||
|
|
e68096bd27 | ||
|
|
50cda426eb | ||
|
|
1038421428 | ||
|
|
a5046ab086 | ||
|
|
ebbec1954e | ||
|
|
4021018931 | ||
|
|
5824c3cb7c | ||
|
|
45a1b9471e | ||
|
|
70bc819665 | ||
|
|
e05f3e9b9c | ||
|
|
e93f1ab6f4 | ||
|
|
0878a8ecf0 | ||
|
|
6ea07139dc | ||
|
|
55fca2d7d5 | ||
|
|
8596dcef21 | ||
|
|
bca84d5508 | ||
|
|
65f7485497 | ||
|
|
457b02c781 | ||
|
|
c8e0fa85f3 | ||
|
|
5e714f6143 | ||
|
|
4ecbf31898 | ||
|
|
ea24bf0415 | ||
|
|
171f8349cb | ||
|
|
398f8d001f | ||
|
|
e66978fb48 | ||
|
|
c57d528db7 | ||
|
|
0c47310063 | ||
|
|
cb4f6e37a8 | ||
|
|
ab943f36c3 | ||
|
|
de7fc78ef0 | ||
|
|
9a502580fd | ||
|
|
d56e70b995 | ||
|
|
e9aaf50d59 | ||
|
|
ac0a4f521a | ||
|
|
a3380c5cdd | ||
|
|
6a6d2a0787 | ||
|
|
64809d9ae2 | ||
|
|
d14b38bc91 | ||
|
|
440dfb5785 | ||
|
|
d4a4b5f4fb | ||
|
|
0c000a7fee | ||
|
|
c655c2a20e | ||
|
|
3ba5a18b91 | ||
|
|
bdb3415855 | ||
|
|
5ef5bdd9d9 | ||
|
|
c7bbce8371 | ||
|
|
5e2c26a4a2 | ||
|
|
631faa20ec | ||
|
|
2db17ba67c | ||
|
|
50eca42e35 | ||
|
|
f327487157 | ||
|
|
85b64b7ac3 | ||
|
|
cf17a9e8d6 | ||
|
|
71a1282b89 | ||
|
|
85e1f2f47d | ||
|
|
1f68eba146 | ||
|
|
d71873442f | ||
|
|
10ca2da2d6 | ||
|
|
c7ba822320 | ||
|
|
ef3ce46d00 | ||
|
|
c4595e03ce | ||
|
|
26a7eb456b | ||
|
|
142a85d6a7 | ||
|
|
ef51490a1a | ||
|
|
c40d643238 | ||
|
|
6f23c88567 | ||
|
|
56958a6242 | ||
|
|
74dac97b36 | ||
|
|
2f2e41c781 | ||
|
|
8c872f71c6 | ||
|
|
b40b496866 | ||
|
|
569fec296e | ||
|
|
56d8aa797a | ||
|
|
fe7e30b737 | ||
|
|
a114281c60 | ||
|
|
d09548d04d | ||
|
|
a02b8e3e5c | ||
|
|
2c3f9ca202 | ||
|
|
587782820d | ||
|
|
8fad048569 | ||
|
|
f7c35b118e | ||
|
|
65a669bbb2 | ||
|
|
9985acc539 | ||
|
|
f1f0a43f21 | ||
|
|
6b856c3cc5 | ||
|
|
d92888ed73 | ||
|
|
0357840654 | ||
|
|
53cae3a66d | ||
|
|
949a1ca4ae | ||
|
|
e667536a5b | ||
|
|
dde000a4bb | ||
|
|
aa1f5a8e7d | ||
|
|
bfbfcc2894 | ||
|
|
6abfa759aa | ||
|
|
7cbac2e757 | ||
|
|
1012381d3d | ||
|
|
6de96f62df | ||
|
|
e2ed2bdbf6 | ||
|
|
e248c54aa5 | ||
|
|
1c9635edad | ||
|
|
25cf6c52e4 | ||
|
|
7859ef6145 | ||
|
|
6efaa4ac7e | ||
|
|
19e17a8431 | ||
|
|
c865ae9734 | ||
|
|
6959f74073 | ||
|
|
9f4d21e976 | ||
|
|
719f39c01c | ||
|
|
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 | ||
|
|
8f17873da2 | ||
|
|
b0cac776ee | ||
|
|
625dba4d85 |
7
.flowconfig
Normal file
7
.flowconfig
Normal file
@@ -0,0 +1,7 @@
|
||||
[ignore]
|
||||
|
||||
[include]
|
||||
|
||||
[libs]
|
||||
|
||||
[options]
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -17,7 +17,7 @@
|
||||
|
||||
# Ignore object files.
|
||||
*.o
|
||||
build/*.js
|
||||
build/
|
||||
tags
|
||||
bin/rippled
|
||||
Debug/*.*
|
||||
@@ -25,6 +25,7 @@ Release/*.*
|
||||
|
||||
# Ignore locally installed node_modules
|
||||
node_modules
|
||||
!test/node_modules
|
||||
|
||||
# Ignore tmp directory.
|
||||
tmp
|
||||
@@ -52,3 +53,11 @@ npm-debug.log
|
||||
|
||||
# Ignore dist folder, build for bower
|
||||
dist/
|
||||
|
||||
# Ignore flow output directory
|
||||
out/
|
||||
|
||||
# Ignore perf test cache
|
||||
scripts/cache
|
||||
|
||||
eslintrc
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
deploy
|
||||
lib-cov
|
||||
coverage.html
|
||||
src
|
||||
dist/bower
|
||||
|
||||
11
.travis.yml
11
.travis.yml
@@ -1,13 +1,18 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
script: npm test --coverage
|
||||
- "0.12"
|
||||
before_script:
|
||||
- npm install -g eslint
|
||||
- curl 'https://raw.githubusercontent.com/ripple/javascript-style-guide/es6/eslintrc' > ./eslintrc
|
||||
- eslint --reset -c ./eslintrc $(git --no-pager diff --name-only -M100% --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
|
||||
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
|
||||
on_start: false # default: false
|
||||
|
||||
237
Gulpfile.js
237
Gulpfile.js
@@ -1,163 +1,156 @@
|
||||
/* eslint-disable no-var, no-param-reassign */
|
||||
/* these eslint rules are disabled because gulp does not support babel yet */
|
||||
'use strict';
|
||||
var _ = require('lodash');
|
||||
var gulp = require('gulp');
|
||||
var concat = require('gulp-concat');
|
||||
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 uglify = require('gulp-uglify');
|
||||
var rename = require('gulp-rename');
|
||||
var webpack = require('webpack');
|
||||
var jshint = require('gulp-jshint');
|
||||
var map = require('map-stream');
|
||||
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 banner = '/*! <%= pkg.name %> - v<%= pkg.version %> - '
|
||||
+ '<%= new Date().toISOString() %>\n'
|
||||
+ '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>'
|
||||
+ '* Copyright (c) <%= new Date().getFullYear() %> <%= pkg.author.name %>;'
|
||||
+ ' Licensed <%= pkg.license %> */'
|
||||
|
||||
var sjclSrc = [
|
||||
'src/js/sjcl/core/sjcl.js',
|
||||
'src/js/sjcl/core/aes.js',
|
||||
'src/js/sjcl/core/bitArray.js',
|
||||
'src/js/sjcl/core/codecString.js',
|
||||
'src/js/sjcl/core/codecHex.js',
|
||||
'src/js/sjcl/core/codecBase64.js',
|
||||
'src/js/sjcl/core/codecBytes.js',
|
||||
'src/js/sjcl/core/sha256.js',
|
||||
'src/js/sjcl/core/sha512.js',
|
||||
'src/js/sjcl/core/sha1.js',
|
||||
'src/js/sjcl/core/ccm.js',
|
||||
// 'src/js/sjcl/core/cbc.js',
|
||||
// 'src/js/sjcl/core/ocb2.js',
|
||||
'src/js/sjcl/core/hmac.js',
|
||||
'src/js/sjcl/core/pbkdf2.js',
|
||||
'src/js/sjcl/core/random.js',
|
||||
'src/js/sjcl/core/convenience.js',
|
||||
'src/js/sjcl/core/bn.js',
|
||||
'src/js/sjcl/core/ecc.js',
|
||||
'src/js/sjcl/core/srp.js',
|
||||
'src/js/sjcl-custom/sjcl-ecc-pointextras.js',
|
||||
'src/js/sjcl-custom/sjcl-secp256k1.js',
|
||||
'src/js/sjcl-custom/sjcl-ripemd160.js',
|
||||
'src/js/sjcl-custom/sjcl-extramath.js',
|
||||
'src/js/sjcl-custom/sjcl-montgomery.js',
|
||||
'src/js/sjcl-custom/sjcl-validecc.js',
|
||||
'src/js/sjcl-custom/sjcl-ecdsa-canonical.js',
|
||||
'src/js/sjcl-custom/sjcl-ecdsa-der.js',
|
||||
'src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js',
|
||||
'src/js/sjcl-custom/sjcl-jacobi.js'
|
||||
];
|
||||
|
||||
gulp.task('concat-sjcl', function() {
|
||||
return gulp.src(sjclSrc)
|
||||
.pipe(concat('sjcl.js'))
|
||||
.pipe(gulp.dest('./build/'));
|
||||
});
|
||||
|
||||
gulp.task('build', [ 'concat-sjcl' ], function(callback) {
|
||||
webpack({
|
||||
function webpackConfig(extension, overrides) {
|
||||
overrides = overrides || {};
|
||||
var defaults = {
|
||||
cache: true,
|
||||
entry: './src/js/ripple/index.js',
|
||||
entry: './src/index.js',
|
||||
output: {
|
||||
library: 'ripple',
|
||||
path: './build/',
|
||||
filename: [ 'ripple-', '.js' ].join(pkg.version)
|
||||
filename: ['ripple-', extension].join(pkg.version)
|
||||
},
|
||||
}, callback);
|
||||
module: {
|
||||
loaders: [{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules/,
|
||||
loader: 'babel-loader?optional=runtime'
|
||||
}]
|
||||
}
|
||||
};
|
||||
return _.assign({}, defaults, overrides);
|
||||
}
|
||||
|
||||
function logPluginError(error) {
|
||||
gutil.log(error.toString());
|
||||
}
|
||||
|
||||
gulp.task('build', function(callback) {
|
||||
webpack(webpackConfig('.js'), callback);
|
||||
});
|
||||
|
||||
gulp.task('bower-build', [ 'build' ], function(callback) {
|
||||
return gulp.src([ './build/ripple-', '.js' ].join(pkg.version))
|
||||
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', function(callback) {
|
||||
var configOverrides = {debug: true, devtool: 'eval'};
|
||||
webpack(webpackConfig('-debug.js', configOverrides), 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', function(callback) {
|
||||
var configOverrides = {
|
||||
cache: false,
|
||||
entry: './src/remote.js',
|
||||
externals: [{
|
||||
'./transaction': buildUseError('Transaction'),
|
||||
'./orderbook': buildUseError('OrderBook'),
|
||||
'./account': buildUseError('Account'),
|
||||
'./serializedobject': buildUseError('SerializedObject')
|
||||
}],
|
||||
plugins: [
|
||||
new webpack.optimize.UglifyJsPlugin()
|
||||
]
|
||||
};
|
||||
webpack(webpackConfig('-core.js', configOverrides), callback);
|
||||
});
|
||||
|
||||
gulp.task('bower-build', ['build'], function() {
|
||||
return gulp.src(['./build/ripple-', '.js'].join(pkg.version))
|
||||
.pipe(rename('ripple.js'))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
.pipe(gulp.dest('./dist/bower'));
|
||||
});
|
||||
|
||||
gulp.task('bower-build-min', [ 'build-min' ], function(callback) {
|
||||
return gulp.src([ './build/ripple-', '-min.js' ].join(pkg.version))
|
||||
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/'));
|
||||
.pipe(gulp.dest('./dist/bower'));
|
||||
});
|
||||
|
||||
gulp.task('bower-build-debug', [ 'build-debug' ], function(callback) {
|
||||
return gulp.src([ './build/ripple-', '-debug.js' ].join(pkg.version))
|
||||
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/'));
|
||||
.pipe(gulp.dest('./dist/bower'));
|
||||
});
|
||||
|
||||
gulp.task('bower-version', function() {
|
||||
gulp.src('./dist/bower.json')
|
||||
gulp.src('./dist/bower/bower.json')
|
||||
.pipe(bump({version: pkg.version}))
|
||||
.pipe(gulp.dest('./dist/'));
|
||||
.pipe(gulp.dest('./dist/bower'));
|
||||
});
|
||||
|
||||
gulp.task('bower', ['bower-build', 'bower-build-min', 'bower-build-debug',
|
||||
'bower-version']);
|
||||
|
||||
gulp.task('watch', function() {
|
||||
gulp.watch('src/*', ['build-debug']);
|
||||
});
|
||||
|
||||
// To use this, each javascript file must have /* @flow */ on the first line
|
||||
gulp.task('typecheck', function() {
|
||||
return gulp.src('src/*.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')
|
||||
.pipe(watch('src/*.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");
|
||||
throw new Error('No type found, pass it in using the --type argument');
|
||||
}
|
||||
|
||||
gulp.src('./package.json')
|
||||
.pipe(bump({type:argv.type}))
|
||||
.pipe(bump({type: argv.type}))
|
||||
.pipe(gulp.dest('./'));
|
||||
});
|
||||
|
||||
gulp.task('version-beta', function() {
|
||||
gulp.src('./package.json')
|
||||
.pipe(bump({version: pkg.version+'-beta'}))
|
||||
.pipe(bump({version: pkg.version + '-beta'}))
|
||||
.pipe(gulp.dest('./'));
|
||||
});
|
||||
|
||||
gulp.task('build-min', [ 'build' ], function(callback) {
|
||||
return gulp.src([ './build/ripple-', '.js' ].join(pkg.version))
|
||||
.pipe(uglify())
|
||||
.pipe(rename([ 'ripple-', '-min.js' ].join(pkg.version)))
|
||||
.pipe(gulp.dest('./build/'));
|
||||
});
|
||||
|
||||
gulp.task('build-debug', [ 'concat-sjcl' ], function(callback) {
|
||||
webpack({
|
||||
cache: true,
|
||||
entry: './src/js/ripple/index.js',
|
||||
output: {
|
||||
library: 'ripple',
|
||||
path: './build/',
|
||||
filename: [ 'ripple-', '-debug.js' ].join(pkg.version)
|
||||
},
|
||||
debug: true,
|
||||
devtool: 'eval'
|
||||
}, callback);
|
||||
});
|
||||
|
||||
gulp.task('lint', function() {
|
||||
gulp.src('src/js/ripple/*.js')
|
||||
.pipe(jshint())
|
||||
.pipe(map(function(file, callback) {
|
||||
if (!file.jshint.success) {
|
||||
console.log('\nIn', file.path);
|
||||
|
||||
file.jshint.results.forEach(function(err) {
|
||||
if (err && err.error) {
|
||||
var col1 = err.error.line + ':' + err.error.character;
|
||||
var col2 = '[' + err.error.reason + ']';
|
||||
var col3 = '(' + err.error.code + ')';
|
||||
|
||||
while (col1.length < 8) {
|
||||
col1 += ' ';
|
||||
}
|
||||
|
||||
console.log(' ' + [ col1, col2, col3 ].join(' '));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
callback(null, file);
|
||||
}));
|
||||
});
|
||||
|
||||
gulp.task('watch', function() {
|
||||
gulp.watch('src/js/ripple/*', [ 'build-debug' ]);
|
||||
});
|
||||
|
||||
gulp.task('default', [ 'concat-sjcl', 'build', 'build-debug', 'build-min' ]);
|
||||
|
||||
gulp.task('bower', ['bower-build', 'bower-build-min', 'bower-build-debug', 'bower-version']);
|
||||
gulp.task('default', ['build', 'build-debug', 'build-min']);
|
||||
|
||||
200
HISTORY.md
200
HISTORY.md
@@ -1,8 +1,204 @@
|
||||
##0.12.15
|
||||
|
||||
+ [Add offer autobridging](https://github.com/ripple/ripple-lib/commit/c7bbce83719c1e8c6a4fae5ca850e7515db1a4a5)
|
||||
|
||||
+ [Prevent crash when listening for "model" events on the OrderBook class](https://github.com/ripple/ripple-lib/commit/5824c3cb7cb6bd834d6e037f69943aebf3d83351)
|
||||
|
||||
+ [Fix empty order edgecase](https://github.com/ripple/ripple-lib/commit/64809d9ae23dc24f47accd4b4788b48f49880d3e)
|
||||
|
||||
+ [Fix AutobridgeCalculator (RT-3445)](https://github.com/ripple/ripple-lib/commit/1fff5ea6dcbcee856536df26f3b9cf1aec3c3b55)
|
||||
|
||||
+ [Update sjcl and delete custom ripemd160, montgomery, and jacobi](https://github.com/ripple/ripple-lib/commit/50cda426eb83599c38c0b725e1524a01fc415da2)
|
||||
|
||||
+ [Fix transaction summary for transactions that fail with remoteError](https://github.com/ripple/ripple-lib/commit/5e714f6143464d7912f42537acaa553b88eaf6dc)
|
||||
|
||||
+ [Fix serializedobject append for excessively large bytes length](https://github.com/ripple/ripple-lib/commit/e93f1ab6f4aaad347450aee75a169af0faa2121c)
|
||||
|
||||
+ [Switch to sjcl npm module](https://github.com/ripple/ripple-lib/commit/9a502580fd89ec6a9aa55f4e5847f6a4a2cb5bba)
|
||||
|
||||
+ [Add babel transpiler](https://github.com/ripple/ripple-lib/commit/398f8d001f758bf575b959537a17e79e4042d17b)
|
||||
|
||||
+ [Remove unused float.js and wallet.js](https://github.com/ripple/ripple-lib/commit/d4a4b5f4fbbf09677a59ce81bace35c6426a2fda)
|
||||
|
||||
+ [Remove config singleton to reduce global state](https://github.com/ripple/ripple-lib/commit/c655c2a20ee5d150a4b5a1b6717b9fb81f636025)
|
||||
|
||||
##0.12.4
|
||||
|
||||
+ [Improve entropy security](https://github.com/ripple/ripple-lib/commit/c7ba822320880037796f57876d1abb4e525648ed)
|
||||
|
||||
+ [Remove unused crypt.js file](https://github.com/ripple/ripple-lib/commit/1f68eba1461bca03a4d22872450d15ae5a185334)
|
||||
|
||||
##0.12.3
|
||||
|
||||
+ [Add getLedgerSequence to Remote](https://github.com/ripple/ripple-lib/commit/d09548d04d3238fca653d482ec1d5faa7254559a)
|
||||
|
||||
+ [Improve randomness when generating ECDSA signatures](https://github.com/ripple/ripple-lib/commit/fe7e30b737ead6e71adfa466f5835ba546feab31)
|
||||
|
||||
+ [Improve SerializedObject.append performance](https://github.com/ripple/ripple-lib/commit/f7c35b118ebba549a64bcaa1a0629385ec6dbf6f)
|
||||
|
||||
+ [Add `Amount.scale`. Multiply an amount’s value by a scale factor](https://github.com/ripple/ripple-lib/commit/74dac97b368493056474468520f05671f458a69f)
|
||||
|
||||
|
||||
##0.12.2
|
||||
|
||||
+ [Check that stack trace is available, fixes logging in browser](https://github.com/ripple/ripple-lib/commit/53cae3a66d48e88e8a6bbb96d6489ce7b9e22975)
|
||||
|
||||
|
||||
##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)
|
||||
|
||||
+ [Add GlobalFreeze and NoFreeze flags](https://github.com/ripple/ripple-lib/commit/e2ed2bdbf6f01c7d4d690c2cf0b83fba94558dd7)
|
||||
|
||||
+ [Fix handling of falsy parameters in requestLedger](https://github.com/ripple/ripple-lib/commit/6023efed41b7812b3bab660a1c0dc9f0a21000b9)
|
||||
|
||||
+ [Fix Base:decode](https://github.com/ripple/ripple-lib/commit/719f39c01c6941d9a650aa94f95617793dd53ea0)
|
||||
|
||||
+ [Fix Amount: clone in ratio_human, product_human](https://github.com/ripple/ripple-lib/commit/19e17a8431550cf156b1ad669a19dedfe4e28e4a)
|
||||
|
||||
+ [Fix Amount.to_human for very small numbers](https://github.com/ripple/ripple-lib/commit/6abfa759aa09d68074ac558d96c4b126a7cd1719)
|
||||
|
||||
+ [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 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)
|
||||
|
||||
@@ -18,7 +214,7 @@ var options = {
|
||||
ledger: < valid ledger_index or ledger_hash >
|
||||
}
|
||||
|
||||
// The `marker` comes back in an account request if there are more results than are returned
|
||||
// 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 >;
|
||||
|
||||
20
README.md
20
README.md
@@ -9,15 +9,15 @@ A JavaScript API for interacting with Ripple in Node.js and the browser
|
||||
###Features
|
||||
|
||||
+ Connect to a rippled server in JavaScript (Node.js or browser)
|
||||
+ Issue [rippled API](https://ripple.com/wiki/JSON_Messages) requests
|
||||
+ 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
|
||||
|
||||
###In this file
|
||||
|
||||
1. [Installation](README.md#installation)
|
||||
2. [Quickstart](README.md#quickstart)
|
||||
3. [Running tests](https://github.com/ripple/ripple-lib#running-tests)
|
||||
1. [Installation](#installation)
|
||||
2. [Quick start](#quick-start)
|
||||
3. [Running tests](#running-tests)
|
||||
|
||||
###Additional documentation
|
||||
|
||||
@@ -47,7 +47,9 @@ A JavaScript API for interacting with Ripple in Node.js and the browser
|
||||
See the [bower-ripple repo](https://github.com/ripple/bower-ripple) for additional bower instructions
|
||||
|
||||
|
||||
**Building ripple-lib from github**
|
||||
**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
|
||||
@@ -55,9 +57,13 @@ See the [bower-ripple repo](https://github.com/ripple/bower-ripple) for addition
|
||||
$ npm run build
|
||||
```
|
||||
|
||||
Then use the minified `build/ripple-*-min.js`
|
||||
**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>`
|
||||
|
||||
+ `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
|
||||
|
||||
|
||||
@@ -1,47 +1,52 @@
|
||||
#!/usr/bin/env node
|
||||
/* eslint-disable no-var */
|
||||
'use strict';
|
||||
var SerializedObject = require('..').SerializedObject;
|
||||
|
||||
var SerializedObject = require('../src/js/ripple/serializedobject').SerializedObject;
|
||||
function main() {
|
||||
var argv = process.argv.slice(2);
|
||||
var blob = argv.shift();
|
||||
|
||||
var argv = process.argv.slice(2);
|
||||
|
||||
var blob;
|
||||
|
||||
blob = argv.shift();
|
||||
|
||||
if (blob === '-') {
|
||||
read_input(ready);
|
||||
} else {
|
||||
ready();
|
||||
if (blob === '-') {
|
||||
read_input(ready);
|
||||
} else {
|
||||
ready(blob);
|
||||
}
|
||||
}
|
||||
|
||||
function read_input(callback) {
|
||||
tx_json = '';
|
||||
process.stdin.on('data', function(data) { tx_json += data; });
|
||||
var tx_json = '';
|
||||
process.stdin.on('data', function(data) {
|
||||
tx_json += data;
|
||||
});
|
||||
process.stdin.on('end', callback);
|
||||
process.stdin.resume();
|
||||
}
|
||||
|
||||
function ready() {
|
||||
function ready(blob) {
|
||||
var valid_arguments = blob;
|
||||
|
||||
if (!valid_arguments) {
|
||||
console.error('Invalid arguments\n');
|
||||
print_usage();
|
||||
} else {
|
||||
decode();
|
||||
}
|
||||
decode(blob);
|
||||
}
|
||||
}
|
||||
|
||||
function print_usage() {
|
||||
/* eslint-disable max-len */
|
||||
console.log(
|
||||
'Usage: decode_binary.js <hex_blob>\n\n',
|
||||
'Example: decode_binary.js 120000240000000161D6871AFD498D00000000000000000000000000005553440000000000550FC62003E785DC231A1058A05E56E3F09CF4E668400000000000000A732102AE75B908F0A95F740A7BFA96057637E5C2170BC8DAD13B2F7B52AE75FAEBEFCF811450F97A072F1C4357F1AD84566A609479D927C9428314550FC62003E785DC231A1058A05E56E3F09CF4E6'
|
||||
);
|
||||
};
|
||||
/* eslint-enable max-len */
|
||||
}
|
||||
|
||||
function decode() {
|
||||
buffer = new SerializedObject(blob);
|
||||
function decode(blob) {
|
||||
var buffer = new SerializedObject(blob);
|
||||
console.log(buffer.to_json());
|
||||
};
|
||||
}
|
||||
|
||||
main();
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
|
||||
123
bin/rsign.js
123
bin/rsign.js
@@ -1,62 +1,23 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var Transaction = require('../src/js/ripple/transaction').Transaction;
|
||||
|
||||
var argv = process.argv.slice(2);
|
||||
|
||||
var verbose;
|
||||
var secret;
|
||||
var tx_json;
|
||||
|
||||
if (~argv.indexOf('-v')){
|
||||
argv.splice(argv.indexOf('-v'), 1);
|
||||
verbose = true;
|
||||
}
|
||||
|
||||
secret = argv.shift();
|
||||
tx_json = argv.shift();
|
||||
|
||||
if (tx_json === '-') {
|
||||
read_input(ready);
|
||||
} else {
|
||||
ready();
|
||||
}
|
||||
/* eslint-disable no-var */
|
||||
'use strict';
|
||||
var Transaction = require('..').Transaction;
|
||||
|
||||
function read_input(callback) {
|
||||
tx_json = '';
|
||||
process.stdin.on('data', function(data) { tx_json += data; });
|
||||
process.stdin.on('end', callback);
|
||||
var stdin = '';
|
||||
process.stdin.on('data', function(data) {
|
||||
stdin += data;
|
||||
});
|
||||
process.stdin.on('end', function() {
|
||||
callback(stdin);
|
||||
});
|
||||
process.stdin.resume();
|
||||
}
|
||||
|
||||
function ready() {
|
||||
var valid_arguments = secret && tx_json;
|
||||
|
||||
if (!valid_arguments) {
|
||||
console.error('Invalid arguments\n');
|
||||
print_usage();
|
||||
} else {
|
||||
var valid_json = true;
|
||||
|
||||
try {
|
||||
tx_json = JSON.parse(tx_json);
|
||||
} catch(exception) {
|
||||
valid_json = false;
|
||||
}
|
||||
|
||||
if (!valid_json) {
|
||||
console.error('Invalid JSON\n');
|
||||
print_usage();
|
||||
} else {
|
||||
sign_transaction();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function print_usage() {
|
||||
console.log(
|
||||
'Usage: rsign.js <secret> <json>\n\n',
|
||||
'Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC','\''+
|
||||
'Example: rsign.js ssq55ueDob4yV3kPVnNQLHB6icwpC', '\'' +
|
||||
JSON.stringify({
|
||||
TransactionType: 'Payment',
|
||||
Account: 'r3P9vH81KBayazSTrQj6S25jW6kDb779Gi',
|
||||
@@ -64,14 +25,14 @@ function print_usage() {
|
||||
Amount: '200000000',
|
||||
Fee: '10',
|
||||
Sequence: 1
|
||||
})+'\''
|
||||
);
|
||||
};
|
||||
}) + '\''
|
||||
);
|
||||
}
|
||||
|
||||
function sign_transaction() {
|
||||
function sign_transaction(tx_json_object, secret, verbose) {
|
||||
var tx = new Transaction();
|
||||
|
||||
tx.tx_json = tx_json;
|
||||
tx.tx_json = tx_json_object;
|
||||
tx._secret = secret;
|
||||
tx.complete();
|
||||
|
||||
@@ -81,16 +42,56 @@ function sign_transaction() {
|
||||
|
||||
if (verbose) {
|
||||
var sim = { };
|
||||
|
||||
sim.tx_blob = tx.serialize().to_hex();
|
||||
sim.tx_json = tx.tx_json;
|
||||
sim.tx_blob = tx.serialize().to_hex();
|
||||
sim.tx_json = tx.tx_json;
|
||||
sim.tx_signing_hash = unsigned_hash;
|
||||
sim.tx_unsigned = unsigned_blob;
|
||||
|
||||
sim.tx_unsigned = unsigned_blob;
|
||||
console.log(JSON.stringify(sim, null, 2));
|
||||
} else {
|
||||
console.log(tx.serialize().to_hex());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function ready(tx_json, secret, verbose) {
|
||||
if (!(tx_json && secret)) {
|
||||
console.error('Invalid arguments\n');
|
||||
print_usage();
|
||||
return;
|
||||
}
|
||||
|
||||
var tx_json_object;
|
||||
try {
|
||||
tx_json_object = JSON.parse(tx_json);
|
||||
} catch(exception) {
|
||||
console.error('Invalid JSON\n');
|
||||
print_usage();
|
||||
return;
|
||||
}
|
||||
sign_transaction(tx_json_object, secret, verbose);
|
||||
}
|
||||
|
||||
function main() {
|
||||
var argv = process.argv.slice(2);
|
||||
var verbose;
|
||||
var secret;
|
||||
var tx_json;
|
||||
|
||||
if (~argv.indexOf('-v')) {
|
||||
argv.splice(argv.indexOf('-v'), 1);
|
||||
verbose = true;
|
||||
}
|
||||
|
||||
secret = argv.shift();
|
||||
tx_json = argv.shift();
|
||||
|
||||
if (tx_json === '-') {
|
||||
read_input(function(stdin) {
|
||||
ready(stdin, secret, verbose);
|
||||
});
|
||||
} else {
|
||||
ready(tx_json, secret, verbose);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
#!/usr/bin/env node
|
||||
/* eslint-disable no-var */
|
||||
'use strict';
|
||||
var UInt160 = require('..').UInt160;
|
||||
|
||||
var UInt160 = require('../').UInt160;
|
||||
var address = process.argv[2];
|
||||
function main() {
|
||||
var address = process.argv[2];
|
||||
|
||||
if (address === '-') {
|
||||
readInput(validateAddress);
|
||||
} else {
|
||||
validateAddress(address);
|
||||
if (address === '-') {
|
||||
readInput(validateAddress);
|
||||
} else {
|
||||
validateAddress(address);
|
||||
}
|
||||
}
|
||||
|
||||
function readInput(callback) {
|
||||
@@ -19,8 +23,10 @@ function readInput(callback) {
|
||||
process.stdin.on('end', function() {
|
||||
callback(result);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function validateAddress(address) {
|
||||
process.stdout.write((UInt160.is_valid(address.trim()) ? '0' : '1') + '\r\n');
|
||||
};
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
start newcoin
|
||||
sleep 4
|
||||
start index.html
|
||||
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
|
||||
@@ -16,20 +16,9 @@ This file provides step-by-step walkthroughs for some of the most common usages
|
||||
1. [The ripple-lib README](../README.md)
|
||||
2. [The ripple-lib API Reference](REFERENCE.md)
|
||||
|
||||
##Generating a new Ripple Wallet
|
||||
|
||||
```js
|
||||
var Wallet = require('ripple-lib').Wallet;
|
||||
|
||||
var wallet = Wallet.generate();
|
||||
console.log(wallet);
|
||||
// { address: 'rEf4sbVobiiDGExrNj2PkNHGMA8eS6jWh3',
|
||||
// secret: 'shFh4a38EZpEdZxrLifEnVPAoBRce' }
|
||||
```
|
||||
|
||||
##Connecting to the Ripple network
|
||||
|
||||
1. [Get ripple-lib](README.md#getting-ripple-lib)
|
||||
1. [Get ripple-lib](../README.md#installation)
|
||||
2. Load the ripple-lib module into a Node.js file or webpage:
|
||||
```js
|
||||
/* Loading ripple-lib with Node.js */
|
||||
@@ -48,9 +37,9 @@ This file provides step-by-step walkthroughs for some of the most common usages
|
||||
servers: [
|
||||
{ host: 's-west.ripple.com', port: 443, secure: true }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
var remote = new Remote({options});
|
||||
var remote = new Remote(options);
|
||||
|
||||
remote.connect(function(err, res) {
|
||||
/* remote connected, use some remote functions here */
|
||||
@@ -60,10 +49,37 @@ This file provides step-by-step walkthroughs for some of the most common usages
|
||||
|
||||
4. You're connected! Read on to see what to do now.
|
||||
|
||||
##Generating a new Ripple Wallet
|
||||
|
||||
```js
|
||||
var ripple = require('ripple-lib');
|
||||
|
||||
// subscribing to a server allows for more entropy
|
||||
var remote = new ripple.Remote({
|
||||
servers: [
|
||||
{ host: 's1.ripple.com', port: 443, secure: true }
|
||||
]
|
||||
});
|
||||
|
||||
remote.connect(function(err, res) {
|
||||
/* remote connected */
|
||||
});
|
||||
|
||||
// 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' }
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
##Sending rippled API requests
|
||||
|
||||
`Remote` contains functions for constructing a `Request` object.
|
||||
`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.
|
||||
|
||||
@@ -124,29 +140,29 @@ See the [wiki](https://ripple.com/wiki/JSON_Messages#subscribe) for details on s
|
||||
'ledger',
|
||||
'transactions'
|
||||
];
|
||||
|
||||
|
||||
var request = remote.requestSubscribe(streams);
|
||||
|
||||
|
||||
request.on('error', function(error) {
|
||||
console.log('request error: ', error);
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
// 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();
|
||||
});
|
||||
@@ -160,7 +176,7 @@ See the [wiki](https://ripple.com/wiki/JSON_Messages#subscribe) for details on s
|
||||
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;
|
||||
|
||||
@@ -179,8 +195,8 @@ remote.connect(function() {
|
||||
remote.setSecret(MY_ADDRESS, MY_SECRET);
|
||||
|
||||
var transaction = remote.createTransaction('Payment', {
|
||||
account: MY_ADDRESS,
|
||||
destination: RECIPIENT,
|
||||
account: MY_ADDRESS,
|
||||
destination: RECIPIENT,
|
||||
amount: AMOUNT
|
||||
});
|
||||
|
||||
@@ -201,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;
|
||||
|
||||
@@ -225,7 +241,7 @@ remote.connect(function() {
|
||||
|
||||
var transaction = remote.createTransaction('OfferCreate', {
|
||||
account: MY_ADDRESS,
|
||||
taker_pays: '1',
|
||||
taker_pays: '100',
|
||||
taker_gets: '1/USD/' + GATEWAY
|
||||
});
|
||||
|
||||
|
||||
192
npm-shrinkwrap.json
generated
192
npm-shrinkwrap.json
generated
@@ -1,140 +1,86 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.9.0-rc5",
|
||||
"version": "0.12.5",
|
||||
"npm-shrinkwrap-version": "5.4.0",
|
||||
"node-version": "v0.12.6",
|
||||
"dependencies": {
|
||||
"async": {
|
||||
"version": "0.8.0",
|
||||
"from": "async@>=0.8.0 <0.9.0"
|
||||
"version": "0.9.2",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz"
|
||||
},
|
||||
"extend": {
|
||||
"version": "1.2.1",
|
||||
"from": "extend@>=1.2.1 <1.3.0"
|
||||
},
|
||||
"lru-cache": {
|
||||
"version": "2.5.0",
|
||||
"from": "lru-cache@>=2.5.0 <2.6.0"
|
||||
},
|
||||
"ripple-wallet-generator": {
|
||||
"version": "1.0.1",
|
||||
"from": "ripple-wallet-generator@1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ripple-wallet-generator/-/ripple-wallet-generator-1.0.1.tgz"
|
||||
},
|
||||
"superagent": {
|
||||
"version": "0.18.2",
|
||||
"from": "superagent@>=0.18.0 <0.19.0",
|
||||
"babel-runtime": {
|
||||
"version": "5.8.3",
|
||||
"resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-5.8.3.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",
|
||||
"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.5",
|
||||
"from": "combined-stream@>=0.0.4 <0.1.0",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"async": {
|
||||
"version": "0.9.0",
|
||||
"from": "async@>=0.9.0 <0.10.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"readable-stream": {
|
||||
"version": "1.0.27-1",
|
||||
"from": "readable-stream@1.0.27-1",
|
||||
"dependencies": {
|
||||
"core-util-is": {
|
||||
"version": "1.0.1",
|
||||
"from": "core-util-is@>=1.0.0 <1.1.0"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"inherits": {
|
||||
"version": "2.0.1",
|
||||
"from": "inherits@>=2.0.1 <2.1.0"
|
||||
}
|
||||
}
|
||||
"core-js": {
|
||||
"version": "0.9.18",
|
||||
"resolved": "https://registry.npmjs.org/core-js/-/core-js-0.9.18.tgz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"bignumber.js": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-2.0.7.tgz"
|
||||
},
|
||||
"extend": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/extend/-/extend-1.2.1.tgz"
|
||||
},
|
||||
"lodash": {
|
||||
"version": "3.10.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.0.tgz"
|
||||
},
|
||||
"lru-cache": {
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.5.2.tgz"
|
||||
},
|
||||
"ripple-wallet-generator": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/ripple-wallet-generator/-/ripple-wallet-generator-1.0.3.tgz"
|
||||
},
|
||||
"sjcl": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.3.tgz"
|
||||
},
|
||||
"ws": {
|
||||
"version": "0.4.32",
|
||||
"from": "ws@>=0.4.31 <0.5.0",
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-0.7.2.tgz",
|
||||
"dependencies": {
|
||||
"commander": {
|
||||
"version": "2.1.0",
|
||||
"from": "commander@>=2.1.0 <2.2.0"
|
||||
},
|
||||
"nan": {
|
||||
"version": "1.0.0",
|
||||
"from": "nan@>=1.0.0 <1.1.0"
|
||||
},
|
||||
"tinycolor": {
|
||||
"version": "0.0.1",
|
||||
"from": "tinycolor@>=0.0.0 <1.0.0"
|
||||
"bufferutil": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-1.1.0.tgz",
|
||||
"dependencies": {
|
||||
"bindings": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz"
|
||||
},
|
||||
"nan": {
|
||||
"version": "1.8.4",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-1.8.4.tgz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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.2",
|
||||
"resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.2.tgz"
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-1.1.0.tgz",
|
||||
"dependencies": {
|
||||
"bindings": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz"
|
||||
},
|
||||
"nan": {
|
||||
"version": "1.8.4",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-1.8.4.tgz"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
61
package.json
61
package.json
@@ -1,47 +1,64 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.9.2-rc6",
|
||||
"version": "0.12.5",
|
||||
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
|
||||
"files": [
|
||||
"src/js/*",
|
||||
"dist/npm/*",
|
||||
"bin/*",
|
||||
"build/*",
|
||||
"test/*",
|
||||
"Makefile",
|
||||
"Gulpfile.js"
|
||||
],
|
||||
"main": "src/js/ripple",
|
||||
"main": "dist/npm/",
|
||||
"directories": {
|
||||
"test": "test"
|
||||
},
|
||||
"dependencies": {
|
||||
"async": "~0.8.0",
|
||||
"ws": "~0.4.31",
|
||||
"async": "~0.9.0",
|
||||
"babel-runtime": "^5.3.2",
|
||||
"bignumber.js": "^2.0.3",
|
||||
"extend": "~1.2.1",
|
||||
"lodash": "^3.1.0",
|
||||
"lru-cache": "~2.5.0",
|
||||
"superagent": "^0.18.0",
|
||||
"ripple-wallet-generator": "1.0.1"
|
||||
"ripple-wallet-generator": "^1.0.3",
|
||||
"sjcl": "^1.0.3",
|
||||
"ws": "~0.7.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"mocha": "~1.14.0",
|
||||
"gulp": "~3.6.2",
|
||||
"gulp-concat": "~2.2.0",
|
||||
"gulp-jshint": "~1.5.5",
|
||||
"gulp-uglify": "~0.3.0",
|
||||
"gulp-rename": "~1.2.0",
|
||||
"gulp-bump": "~0.1.10",
|
||||
"webpack": "~1.1.11",
|
||||
"map-stream": "~0.1.0",
|
||||
"istanbul": "~0.2.10",
|
||||
"assert-diff": "^1.0.1",
|
||||
"babel": "^5.3.3",
|
||||
"babel-core": "^5.3.2",
|
||||
"babel-loader": "^5.0.0",
|
||||
"coveralls": "~2.10.0",
|
||||
"eslint": "^0.18.0",
|
||||
"gulp": "~3.8.10",
|
||||
"gulp-bump": "~0.1.13",
|
||||
"gulp-clean-dest": "^0.1.0",
|
||||
"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": {
|
||||
"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 spec test/*-test.js",
|
||||
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
|
||||
"build": "gulp",
|
||||
"compile": "babel -i runtime -d dist/npm/ src/",
|
||||
"compile-with-source-maps": "babel -i runtime -s -t -d dist/npm/ src/",
|
||||
"prepublish": "npm run compile",
|
||||
"postinstall": "cd node_modules/sjcl; ./configure --with-all --compress=none; make",
|
||||
"test": "istanbul test _mocha",
|
||||
"coveralls": "cat ./coverage/lcov.info | coveralls",
|
||||
"lint": "if ! [ -f eslintrc ]; then curl -o eslintrc 'https://raw.githubusercontent.com/ripple/javascript-style-guide/es6/eslintrc'; fi; eslint --reset -c eslintrc src/*.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
|
||||
npm run compile && time node "$DIR/verify_ledger_json.js" "$DEST"
|
||||
@@ -17,15 +17,15 @@ echo "publish to npm"
|
||||
npm publish
|
||||
exit_on_error
|
||||
|
||||
rm -rf dist
|
||||
rm -rf dist/bower
|
||||
echo ""
|
||||
echo "publish to bower"
|
||||
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
git clone git@github.com:ripple/bower-ripple.git dist/bower
|
||||
gulp bower
|
||||
exit_on_error
|
||||
|
||||
cd dist
|
||||
cd dist/bower
|
||||
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
|
||||
@@ -40,4 +40,4 @@ exit_on_error
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
|
||||
cd ..
|
||||
cd ..
|
||||
|
||||
@@ -17,15 +17,15 @@ echo "publish rc to npm"
|
||||
npm publish --tag beta
|
||||
exit_on_error
|
||||
|
||||
rm -rf dist
|
||||
rm -rf dist/bower
|
||||
echo ""
|
||||
echo "publish to bower"
|
||||
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
git clone git@github.com:ripple/bower-ripple.git dist/bower
|
||||
gulp bower
|
||||
exit_on_error
|
||||
|
||||
cd dist
|
||||
cd dist/bower
|
||||
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
|
||||
@@ -40,4 +40,4 @@ exit_on_error
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
|
||||
cd ..
|
||||
cd ..
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
rm -rf dist
|
||||
git clone git@github.com:ripple/bower-ripple.git dist
|
||||
rm -rf dist/bower
|
||||
git clone git@github.com:ripple/bower-ripple.git dist/bower
|
||||
gulp bower
|
||||
cd dist
|
||||
cd dist/bower
|
||||
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
|
||||
@@ -9,4 +9,4 @@ git commit -m "[TASK] add v$version"
|
||||
git tag "v$version"
|
||||
git push origin master
|
||||
git push --tags origin master
|
||||
cd ..
|
||||
cd ..
|
||||
|
||||
@@ -1,31 +1,35 @@
|
||||
/* eslint-disable no-var */
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var Ledger = require('../src/js/ripple/ledger').Ledger;
|
||||
var Amount = require('../dist/npm').Amount;
|
||||
var Ledger = require('../dist/npm/ledger').Ledger;
|
||||
|
||||
function parse_options(from, flags) {
|
||||
var argv = from.slice(),
|
||||
opts = {argv:argv};
|
||||
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]) {
|
||||
var flag = f.replace('-', '_');
|
||||
// opts_ has Boolean value for normalized flag key
|
||||
opts_[flag] = flag_index !== -1;
|
||||
if (opts_[flag]) {
|
||||
// remove the flag from the argv
|
||||
argv.splice(flag_index, 1);
|
||||
}
|
||||
});
|
||||
return opts;
|
||||
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)");
|
||||
console.error('Usage: scripts/verify_ledger_json path/to/ledger.json');
|
||||
console.error(' optional: --sanity-test (json>binary>json>binary)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -36,14 +40,27 @@ var ledger = Ledger.from_json(JSON.parse(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('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());
|
||||
// To recompute the hashes of some ledgers, we must allow values that slipped in
|
||||
// before strong policies were in place.
|
||||
Amount.strict_mode = false;
|
||||
|
||||
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);
|
||||
|
||||
if (ledger.ledger_json.accountState) {
|
||||
console.log('Calculated account state hash: ' +
|
||||
ledger.calc_account_hash({sanity_test: opts.sanity_test})
|
||||
.to_hex());
|
||||
} else {
|
||||
console.log('Ledger has no accountState');
|
||||
}
|
||||
|
||||
@@ -45,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;
|
||||
}
|
||||
@@ -59,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();
|
||||
}
|
||||
}
|
||||
};
|
||||
1011
src/amount.js
Normal file
1011
src/amount.js
Normal file
File diff suppressed because it is too large
Load Diff
437
src/autobridgecalculator.js
Normal file
437
src/autobridgecalculator.js
Normal file
@@ -0,0 +1,437 @@
|
||||
'use strict';
|
||||
|
||||
const _ = require('lodash');
|
||||
const assert = require('assert');
|
||||
const UInt160 = require('./uint160').UInt160;
|
||||
const Amount = require('./amount').Amount;
|
||||
const Utils = require('./orderbookutils');
|
||||
|
||||
function assertValidNumber(number, message) {
|
||||
assert(!_.isNull(number) && !isNaN(number), message);
|
||||
}
|
||||
|
||||
function assertValidLegOneOffer(legOneOffer, message) {
|
||||
assert(legOneOffer);
|
||||
assert.strictEqual(typeof legOneOffer, 'object', message);
|
||||
assert.strictEqual(typeof legOneOffer.TakerPays, 'object', message);
|
||||
assertValidNumber(legOneOffer.TakerGets, message);
|
||||
}
|
||||
|
||||
function AutobridgeCalculator(currencyGets, currencyPays,
|
||||
legOneOffers, legTwoOffers, issuerGets, issuerPays) {
|
||||
this._currencyGets = currencyGets;
|
||||
this._currencyPays = currencyPays;
|
||||
this._issuerGets = issuerGets;
|
||||
this._issuerPays = issuerPays;
|
||||
this.legOneOffers = _.cloneDeep(legOneOffers);
|
||||
this.legTwoOffers = _.cloneDeep(legTwoOffers);
|
||||
|
||||
this._ownerFundsLeftover = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates an ordered array of autobridged offers by quality
|
||||
*
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.calculate = function() {
|
||||
let legOnePointer = 0;
|
||||
let legTwoPointer = 0;
|
||||
|
||||
let offersAutobridged = [];
|
||||
|
||||
this.clearOwnerFundsLeftover();
|
||||
|
||||
while (this.legOneOffers[legOnePointer] && this.legTwoOffers[legTwoPointer]) {
|
||||
const legOneOffer = this.legOneOffers[legOnePointer];
|
||||
const legTwoOffer = this.legTwoOffers[legTwoPointer];
|
||||
const leftoverFunds = this.getLeftoverOwnerFunds(legOneOffer.Account);
|
||||
let autobridgedOffer;
|
||||
|
||||
if (legOneOffer.Account === legTwoOffer.Account) {
|
||||
this.unclampLegOneOwnerFunds(legOneOffer);
|
||||
} else if (!legOneOffer.is_fully_funded && !leftoverFunds.is_zero()) {
|
||||
this.adjustLegOneFundedAmount(legOneOffer);
|
||||
}
|
||||
|
||||
const legOneTakerGetsFunded = Utils.getOfferTakerGetsFunded(legOneOffer);
|
||||
const legTwoTakerPaysFunded = Utils.getOfferTakerPaysFunded(legTwoOffer);
|
||||
|
||||
if (legOneTakerGetsFunded.is_zero()) {
|
||||
legOnePointer++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (legTwoTakerPaysFunded.is_zero()) {
|
||||
legTwoPointer++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (legOneTakerGetsFunded.compareTo(legTwoTakerPaysFunded) > 0) {
|
||||
autobridgedOffer = this.getAutobridgedOfferWithClampedLegOne(
|
||||
legOneOffer,
|
||||
legTwoOffer
|
||||
);
|
||||
|
||||
legTwoPointer++;
|
||||
} else if (legTwoTakerPaysFunded.compareTo(legOneTakerGetsFunded) > 0) {
|
||||
autobridgedOffer = this.getAutobridgedOfferWithClampedLegTwo(
|
||||
legOneOffer,
|
||||
legTwoOffer
|
||||
);
|
||||
|
||||
legOnePointer++;
|
||||
} else {
|
||||
autobridgedOffer = this.getAutobridgedOfferWithoutClamps(
|
||||
legOneOffer,
|
||||
legTwoOffer
|
||||
);
|
||||
|
||||
legOnePointer++;
|
||||
legTwoPointer++;
|
||||
}
|
||||
|
||||
offersAutobridged.push(autobridgedOffer);
|
||||
}
|
||||
|
||||
return offersAutobridged;
|
||||
};
|
||||
|
||||
/**
|
||||
* In this case, the output from leg one is greater than the input to leg two.
|
||||
* Therefore, we must effectively clamp leg one output to leg two input.
|
||||
*
|
||||
* @param {Object} legOneOffer
|
||||
* @param {Object} legTwoOffer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.getAutobridgedOfferWithClampedLegOne =
|
||||
function(legOneOffer, legTwoOffer) {
|
||||
const legOneTakerGetsFunded = Utils.getOfferTakerGetsFunded(legOneOffer);
|
||||
const legTwoTakerPaysFunded = Utils.getOfferTakerPaysFunded(legTwoOffer);
|
||||
const legOneQuality = Utils.getOfferQuality(legOneOffer, this._currencyGets);
|
||||
|
||||
const autobridgedTakerGets = Utils.getOfferTakerGetsFunded(legTwoOffer);
|
||||
const autobridgedTakerPays = legTwoTakerPaysFunded.multiply(legOneQuality);
|
||||
|
||||
if (legOneOffer.Account === legTwoOffer.Account) {
|
||||
const legOneTakerGets = Utils.getOfferTakerGets(legOneOffer);
|
||||
const updatedTakerGets = legOneTakerGets.subtract(legTwoTakerPaysFunded);
|
||||
|
||||
this.setLegOneTakerGets(legOneOffer, updatedTakerGets);
|
||||
|
||||
this.clampLegOneOwnerFunds(legOneOffer);
|
||||
} else {
|
||||
// Update funded amount since leg one offer was not completely consumed
|
||||
const updatedTakerGetsFunded = legOneTakerGetsFunded
|
||||
.subtract(legTwoTakerPaysFunded);
|
||||
|
||||
this.setLegOneTakerGetsFunded(legOneOffer, updatedTakerGetsFunded);
|
||||
}
|
||||
|
||||
return this.formatAutobridgedOffer(
|
||||
autobridgedTakerGets,
|
||||
autobridgedTakerPays
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* In this case, the input from leg two is greater than the output to leg one.
|
||||
* Therefore, we must effectively clamp leg two input to leg one output.
|
||||
*
|
||||
* @param {Object} legOneOffer
|
||||
* @param {Object} legTwoOffer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.getAutobridgedOfferWithClampedLegTwo =
|
||||
function(legOneOffer, legTwoOffer) {
|
||||
const legOneTakerGetsFunded = Utils.getOfferTakerGetsFunded(legOneOffer);
|
||||
const legTwoTakerPaysFunded = Utils.getOfferTakerPaysFunded(legTwoOffer);
|
||||
const legTwoQuality = Utils.getOfferQuality(legTwoOffer, this._currencyGets);
|
||||
|
||||
const autobridgedTakerGets = legOneTakerGetsFunded.divide(legTwoQuality);
|
||||
const autobridgedTakerPays = Utils.getOfferTakerPaysFunded(legOneOffer);
|
||||
|
||||
// Update funded amount since leg two offer was not completely consumed
|
||||
legTwoOffer.taker_gets_funded = Utils.getOfferTakerGetsFunded(legTwoOffer)
|
||||
.subtract(autobridgedTakerGets)
|
||||
.to_text();
|
||||
legTwoOffer.taker_pays_funded = legTwoTakerPaysFunded
|
||||
.subtract(legOneTakerGetsFunded)
|
||||
.to_text();
|
||||
|
||||
return this.formatAutobridgedOffer(
|
||||
autobridgedTakerGets,
|
||||
autobridgedTakerPays
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* In this case, the output from leg one and the input to leg two are the same.
|
||||
* We do not need to clamp either.
|
||||
* @param {Object} legOneOffer
|
||||
* @param {Object} legTwoOffer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.getAutobridgedOfferWithoutClamps =
|
||||
function(legOneOffer, legTwoOffer) {
|
||||
const autobridgedTakerGets = Utils.getOfferTakerGetsFunded(legTwoOffer);
|
||||
const autobridgedTakerPays = Utils.getOfferTakerPaysFunded(legOneOffer);
|
||||
|
||||
return this.formatAutobridgedOffer(
|
||||
autobridgedTakerGets,
|
||||
autobridgedTakerPays
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear owner funds leftovers
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.clearOwnerFundsLeftover = function() {
|
||||
this._ownerFundsLeftover = {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset owner funds leftovers for an account to 0
|
||||
*
|
||||
* @param {String} account
|
||||
*
|
||||
* @return {Amount}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.resetOwnerFundsLeftover = function(account) {
|
||||
assert(UInt160.is_valid(account), 'Account is invalid');
|
||||
|
||||
this._ownerFundsLeftover[account] = Utils.normalizeAmount('0');
|
||||
|
||||
return this._ownerFundsLeftover[account];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve leftover funds found after clamping leg one by account
|
||||
*
|
||||
* @param {String} account
|
||||
*
|
||||
* @return {Amount}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.getLeftoverOwnerFunds = function(account) {
|
||||
assert(UInt160.is_valid(account), 'Account is invalid');
|
||||
|
||||
let amount = this._ownerFundsLeftover[account];
|
||||
|
||||
if (!amount) {
|
||||
amount = Utils.normalizeAmount('0');
|
||||
}
|
||||
|
||||
return amount;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add funds to account's leftover funds
|
||||
*
|
||||
* @param {String} account
|
||||
* @param {Amount} amount
|
||||
*
|
||||
* @return {Amount}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.addLeftoverOwnerFunds =
|
||||
function(account, amount) {
|
||||
assert(UInt160.is_valid(account), 'Account is invalid');
|
||||
assert(amount instanceof Amount, 'Amount is invalid');
|
||||
|
||||
this._ownerFundsLeftover[account] = this.getLeftoverOwnerFunds(account)
|
||||
.add(amount);
|
||||
|
||||
return this._ownerFundsLeftover[account];
|
||||
};
|
||||
|
||||
/**
|
||||
* Set account's leftover funds
|
||||
*
|
||||
* @param {String} account
|
||||
* @param {Amount} amount
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.setLeftoverOwnerFunds =
|
||||
function(account, amount) {
|
||||
assert(UInt160.is_valid(account), 'Account is invalid');
|
||||
assert(amount instanceof Amount, 'Amount is invalid');
|
||||
|
||||
this._ownerFundsLeftover[account] = amount;
|
||||
};
|
||||
|
||||
/**
|
||||
* Format an autobridged offer and compute synthetic values (e.g. quality)
|
||||
*
|
||||
* @param {Amount} takerGets
|
||||
* @param {Amount} takerPays
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.formatAutobridgedOffer =
|
||||
function(takerGets, takerPays) {
|
||||
assert(takerGets instanceof Amount, 'Autobridged taker gets is invalid');
|
||||
assert(takerPays instanceof Amount, 'Autobridged taker pays is invalid');
|
||||
|
||||
const autobridgedOffer = {};
|
||||
const quality = takerPays.divide(takerGets);
|
||||
|
||||
autobridgedOffer.TakerGets = {
|
||||
value: takerGets.to_text(),
|
||||
currency: this._currencyGets.to_hex(),
|
||||
issuer: this._issuerGets
|
||||
};
|
||||
|
||||
autobridgedOffer.TakerPays = {
|
||||
value: takerPays.to_text(),
|
||||
currency: this._currencyPays.to_hex(),
|
||||
issuer: this._issuerPays
|
||||
};
|
||||
|
||||
autobridgedOffer.quality = quality.to_text();
|
||||
|
||||
autobridgedOffer.taker_gets_funded = autobridgedOffer.TakerGets.value;
|
||||
autobridgedOffer.taker_pays_funded = autobridgedOffer.TakerPays.value;
|
||||
|
||||
autobridgedOffer.autobridged = true;
|
||||
|
||||
autobridgedOffer.BookDirectory = Utils.convertOfferQualityToHex(quality);
|
||||
|
||||
return autobridgedOffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove funds clamp on leg one offer. This is necessary when the two offers
|
||||
* are owned by the same account. In this case, it doesn't matter if offer one
|
||||
* is not fully funded. Leg one out goes to leg two in and since its the same
|
||||
* account, an infinite amount can flow.
|
||||
*
|
||||
* @param {Object} legOneOffer - IOU:XRP offer
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.unclampLegOneOwnerFunds = function(legOneOffer) {
|
||||
assertValidLegOneOffer(legOneOffer, 'Leg one offer is invalid');
|
||||
|
||||
legOneOffer.initTakerGetsFunded = Utils.getOfferTakerGetsFunded(legOneOffer);
|
||||
|
||||
this.setLegOneTakerGetsFunded(
|
||||
legOneOffer,
|
||||
Utils.getOfferTakerGets(legOneOffer)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply clamp back on leg one offer after a round of autobridge calculation
|
||||
* completes. We must reapply clamps that have been removed because we cannot
|
||||
* guarantee that the next offer from leg two will also be from the same
|
||||
* account.
|
||||
*
|
||||
* When we reapply, it could happen that the amount of TakerGets left after
|
||||
* the autobridge calculation is less than the original funded amount. In this
|
||||
* case, we have extra funds we can use towards unfunded offers with worse
|
||||
* quality by the same owner.
|
||||
*
|
||||
* @param {Object} legOneOffer - IOU:XRP offer
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.clampLegOneOwnerFunds = function(legOneOffer) {
|
||||
assertValidLegOneOffer(legOneOffer, 'Leg one offer is invalid');
|
||||
|
||||
const takerGets = Utils.getOfferTakerGets(legOneOffer);
|
||||
|
||||
if (takerGets.compareTo(legOneOffer.initTakerGetsFunded) > 0) {
|
||||
// After clamping, TakerGets is still greater than initial funded amount
|
||||
this.setLegOneTakerGetsFunded(legOneOffer, legOneOffer.initTakerGetsFunded);
|
||||
} else {
|
||||
const updatedLeftover = legOneOffer.initTakerGetsFunded.subtract(takerGets);
|
||||
|
||||
this.setLegOneTakerGetsFunded(legOneOffer, takerGets);
|
||||
this.addLeftoverOwnerFunds(legOneOffer.Account, updatedLeftover);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Increase leg one offer funded amount with extra funds found after applying
|
||||
* clamp.
|
||||
*
|
||||
* @param {Object} legOneOffer - IOU:XRP offer
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.adjustLegOneFundedAmount =
|
||||
function(legOneOffer) {
|
||||
assertValidLegOneOffer(legOneOffer, 'Leg one offer is invalid');
|
||||
assert(!legOneOffer.is_fully_funded, 'Leg one offer cannot be fully funded');
|
||||
|
||||
const fundedSum = Utils.getOfferTakerGetsFunded(legOneOffer)
|
||||
.add(this.getLeftoverOwnerFunds(legOneOffer.Account));
|
||||
|
||||
if (fundedSum.compareTo(Utils.getOfferTakerGets(legOneOffer)) >= 0) {
|
||||
// There are enough extra funds to fully fund the offer
|
||||
const legOneTakerGets = Utils.getOfferTakerGets(legOneOffer);
|
||||
const updatedLeftover = fundedSum.subtract(legOneTakerGets);
|
||||
|
||||
this.setLegOneTakerGetsFunded(legOneOffer, legOneTakerGets);
|
||||
this.setLeftoverOwnerFunds(legOneOffer.Account, updatedLeftover);
|
||||
} else {
|
||||
// There are not enough extra funds to fully fund the offer
|
||||
this.setLegOneTakerGetsFunded(legOneOffer, fundedSum);
|
||||
this.resetOwnerFundsLeftover(legOneOffer.Account);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Set taker gets funded amount for a IOU:XRP offer. Also calculates taker
|
||||
* pays funded using offer quality and updates is_fully_funded flag
|
||||
*
|
||||
* @param {Object} legOneOffer - IOU:XRP offer
|
||||
* @param {Amount} takerGetsFunded
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.setLegOneTakerGetsFunded =
|
||||
function setLegOneTakerGetsFunded(legOneOffer, takerGetsFunded) {
|
||||
assertValidLegOneOffer(legOneOffer, 'Leg one offer is invalid');
|
||||
assert(takerGetsFunded instanceof Amount, 'Taker gets funded is invalid');
|
||||
|
||||
legOneOffer.taker_gets_funded = takerGetsFunded.to_text();
|
||||
legOneOffer.taker_pays_funded = takerGetsFunded
|
||||
.multiply(Utils.getOfferQuality(legOneOffer, this._currencyGets))
|
||||
.to_text();
|
||||
|
||||
if (legOneOffer.taker_gets_funded === legOneOffer.TakerGets.value) {
|
||||
legOneOffer.is_fully_funded = true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Set taker gets amount for a IOU:XRP offer. Also calculates taker pays
|
||||
* using offer quality
|
||||
*
|
||||
* @param {Object} legOneOffer - IOU:XRP offer
|
||||
* @param {Amount} takerGets
|
||||
*/
|
||||
|
||||
AutobridgeCalculator.prototype.setLegOneTakerGets =
|
||||
function(legOneOffer, takerGets) {
|
||||
assertValidLegOneOffer(legOneOffer, 'Leg one offer is invalid');
|
||||
assert(takerGets instanceof Amount, 'Taker gets funded is invalid');
|
||||
|
||||
const legOneQuality = Utils.getOfferQuality(legOneOffer, this._currencyGets);
|
||||
|
||||
legOneOffer.TakerGets = takerGets.to_text();
|
||||
legOneOffer.TakerPays = takerGets.multiply(legOneQuality);
|
||||
};
|
||||
|
||||
module.exports = AutobridgeCalculator;
|
||||
154
src/base.js
Normal file
154
src/base.js
Normal file
@@ -0,0 +1,154 @@
|
||||
'use strict';
|
||||
const _ = require('lodash');
|
||||
const sjcl = require('./utils').sjcl;
|
||||
const utils = require('./utils');
|
||||
const extend = require('extend');
|
||||
const convertBase = require('./baseconverter');
|
||||
|
||||
const Base = {};
|
||||
|
||||
const alphabets = Base.alphabets = {
|
||||
ripple: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz',
|
||||
tipple: 'RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz',
|
||||
bitcoin: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
||||
};
|
||||
|
||||
extend(Base, {
|
||||
VER_NONE: 1,
|
||||
VER_NODE_PUBLIC: 28,
|
||||
VER_NODE_PRIVATE: 32,
|
||||
VER_ACCOUNT_ID: 0,
|
||||
VER_ACCOUNT_PUBLIC: 35,
|
||||
VER_ACCOUNT_PRIVATE: 34,
|
||||
VER_FAMILY_GENERATOR: 41,
|
||||
VER_FAMILY_SEED: 33
|
||||
});
|
||||
|
||||
function sha256(bytes) {
|
||||
return sjcl.codec.bytes.fromBits(
|
||||
sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
|
||||
}
|
||||
|
||||
function encodeString(alphabet, input) {
|
||||
if (input.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const leadingZeros = _.takeWhile(input, function(d) {
|
||||
return d === 0;
|
||||
});
|
||||
const 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];
|
||||
});
|
||||
const prefix = leadingZeros.map(function() {
|
||||
return alphabet[0];
|
||||
});
|
||||
return prefix.concat(out).join('');
|
||||
}
|
||||
|
||||
function decodeString(indexes, input) {
|
||||
if (input.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const input58 = input.split('').map(function(c) {
|
||||
const charCode = c.charCodeAt(0);
|
||||
if (charCode >= indexes.length || indexes[charCode] === -1) {
|
||||
throw new Error('Character ' + c + ' is not valid for encoding');
|
||||
}
|
||||
return indexes[charCode];
|
||||
});
|
||||
const leadingZeros = _.takeWhile(input58, function(d) {
|
||||
return d === 0;
|
||||
});
|
||||
const out = convertBase(input58, 58, 256);
|
||||
return leadingZeros.concat(out);
|
||||
}
|
||||
|
||||
function Base58(alphabet) {
|
||||
const indexes = utils.arraySet(128, -1);
|
||||
for (let 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) {
|
||||
return this.encoders[alpha || 'ripple'].encode(input);
|
||||
};
|
||||
|
||||
// --> input: String
|
||||
// <-- array of bytes or undefined.
|
||||
Base.decode = function(input, alpha) {
|
||||
if (typeof input !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return this.encoders[alpha || 'ripple'].decode(input);
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
Base.verify_checksum = function(bytes) {
|
||||
const computed = sha256(sha256(bytes.slice(0, -4))).slice(0, 4);
|
||||
const checksum = bytes.slice(-4);
|
||||
return _.isEqual(computed, checksum);
|
||||
};
|
||||
|
||||
// --> input: Array
|
||||
// <-- String
|
||||
Base.encode_check = function(version, input, alphabet) {
|
||||
const buffer = [].concat(version, input);
|
||||
const check = sha256(sha256(buffer)).slice(0, 4);
|
||||
|
||||
return Base.encode([].concat(buffer, check), alphabet);
|
||||
};
|
||||
|
||||
// --> input : String
|
||||
// <-- NaN || sjcl.bn
|
||||
Base.decode_check = function(version, input, alphabet) {
|
||||
const buffer = Base.decode(input, alphabet);
|
||||
|
||||
if (!buffer || buffer.length < 5) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// Single valid version
|
||||
if (typeof version === 'number' && buffer[0] !== version) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// Multiple allowed versions
|
||||
if (Array.isArray(version) && _.every(version, function(v) {
|
||||
return v !== buffer[0];
|
||||
})) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
if (!Base.verify_checksum(buffer)) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// We'll use the version byte to add a leading zero, this ensures JSBN doesn't
|
||||
// intrepret the value as a negative number
|
||||
buffer[0] = 0;
|
||||
|
||||
return sjcl.bn.fromBits(
|
||||
sjcl.codec.bytes.toBits(buffer.slice(0, -4)));
|
||||
};
|
||||
|
||||
exports.Base = Base;
|
||||
32
src/baseconverter.js
Normal file
32
src/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
|
||||
@@ -39,7 +48,7 @@ var TYPES_MAP = exports.types = [
|
||||
* Mapping of field type id to field type name.
|
||||
*/
|
||||
|
||||
var FIELDS_MAP = exports.fields = {
|
||||
const FIELDS_MAP = exports.fields = {
|
||||
// Common types
|
||||
1: { // Int16
|
||||
1: 'LedgerEntryType',
|
||||
@@ -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,11 +198,11 @@ var FIELDS_MAP = exports.fields = {
|
||||
19: { // Vector256
|
||||
1: 'Indexes',
|
||||
2: 'Hashes',
|
||||
3: 'Features'
|
||||
3: 'Amendments'
|
||||
}
|
||||
};
|
||||
|
||||
var INVERSE_FIELDS_MAP = exports.fieldsInverseMap = { };
|
||||
let INVERSE_FIELDS_MAP = exports.fieldsInverseMap = { };
|
||||
|
||||
Object.keys(FIELDS_MAP).forEach(function(k1) {
|
||||
Object.keys(FIELDS_MAP[k1]).forEach(function(k2) {
|
||||
@@ -199,12 +210,11 @@ Object.keys(FIELDS_MAP).forEach(function(k1) {
|
||||
});
|
||||
});
|
||||
|
||||
const REQUIRED = exports.REQUIRED = 0,
|
||||
OPTIONAL = exports.OPTIONAL = 1,
|
||||
DEFAULT = exports.DEFAULT = 2;
|
||||
|
||||
var REQUIRED = exports.REQUIRED = 0,
|
||||
OPTIONAL = exports.OPTIONAL = 1,
|
||||
DEFAULT = exports.DEFAULT = 2;
|
||||
|
||||
var base = [
|
||||
const base = [
|
||||
[ 'TransactionType' , REQUIRED ],
|
||||
[ 'Flags' , OPTIONAL ],
|
||||
[ 'SourceTag' , OPTIONAL ],
|
||||
@@ -214,7 +224,9 @@ var base = [
|
||||
[ 'Fee' , REQUIRED ],
|
||||
[ 'OperationLimit' , OPTIONAL ],
|
||||
[ 'SigningPubKey' , REQUIRED ],
|
||||
[ 'TxnSignature' , OPTIONAL ]
|
||||
[ 'TxnSignature' , OPTIONAL ],
|
||||
[ 'AccountTxnID' , OPTIONAL ],
|
||||
[ 'Memos' , OPTIONAL ]
|
||||
];
|
||||
|
||||
exports.tx = {
|
||||
@@ -224,7 +236,9 @@ exports.tx = {
|
||||
[ 'WalletSize' , OPTIONAL ],
|
||||
[ 'MessageKey' , OPTIONAL ],
|
||||
[ 'Domain' , OPTIONAL ],
|
||||
[ 'TransferRate' , OPTIONAL ]
|
||||
[ 'TransferRate' , OPTIONAL ],
|
||||
[ 'SetFlag' , OPTIONAL ],
|
||||
[ 'ClearFlag' , OPTIONAL ]
|
||||
]),
|
||||
TrustSet: [20].concat(base, [
|
||||
[ 'LimitAmount' , OPTIONAL ],
|
||||
@@ -234,13 +248,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 ],
|
||||
@@ -266,16 +281,25 @@ 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 ]
|
||||
])
|
||||
};
|
||||
|
||||
var sleBase = [
|
||||
const sleBase = [
|
||||
['LedgerIndex', OPTIONAL],
|
||||
['LedgerEntryType', REQUIRED],
|
||||
['Flags', REQUIRED]
|
||||
@@ -373,7 +397,7 @@ exports.ledger = {
|
||||
['Balance', REQUIRED],
|
||||
['LowLimit', REQUIRED],
|
||||
['HighLimit', REQUIRED]])
|
||||
}
|
||||
};
|
||||
|
||||
exports.metadata = [
|
||||
[ 'TransactionIndex' , REQUIRED ],
|
||||
@@ -409,5 +433,8 @@ exports.ter = {
|
||||
tecNO_TARGET : 138,
|
||||
tecNO_PERMISSION : 139,
|
||||
tecNO_ENTRY : 140,
|
||||
tecINSUFFICIENT_RESERVE : 141
|
||||
tecINSUFFICIENT_RESERVE : 141,
|
||||
tecNEED_MASTER_KEY : 142,
|
||||
tecDST_TAG_NEEDED : 143,
|
||||
tecINTERNAL : 144
|
||||
};
|
||||
@@ -1,126 +0,0 @@
|
||||
#include "TransactionErr.h"
|
||||
#include "utils.h"
|
||||
|
||||
bool transResultInfo(TER terCode, std::string& strToken, std::string& strHuman)
|
||||
{
|
||||
static struct {
|
||||
TER terCode;
|
||||
const char* cpToken;
|
||||
const char* cpHuman;
|
||||
} transResultInfoA[] = {
|
||||
{ tecCLAIM, "tecCLAIM", "Fee claimed. Sequence used. No action." },
|
||||
{ tecDIR_FULL, "tecDIR_FULL", "Can not add entry to full directory." },
|
||||
{ tecFAILED_PROCESSING, "tecFAILED_PROCESSING", "Failed to correctly process transaction." },
|
||||
{ tecINSUF_RESERVE_LINE, "tecINSUF_RESERVE_LINE", "Insufficient reserve to add trust line." },
|
||||
{ tecINSUF_RESERVE_OFFER, "tecINSUF_RESERVE_OFFER", "Insufficient reserve to create offer." },
|
||||
{ tecNO_DST, "tecNO_DST", "Destination does not exist. Send XRP to create it." },
|
||||
{ tecNO_DST_INSUF_XRP, "tecNO_DST_INSUF_XRP", "Destination does not exist. Too little XRP sent to create it." },
|
||||
{ tecNO_LINE_INSUF_RESERVE, "tecNO_LINE_INSUF_RESERVE", "No such line. Too little reserve to create it." },
|
||||
{ tecNO_LINE_REDUNDANT, "tecNO_LINE_REDUNDANT", "Can't set non-existant line to default." },
|
||||
{ tecPATH_DRY, "tecPATH_DRY", "Path could not send partial amount." },
|
||||
{ tecPATH_PARTIAL, "tecPATH_PARTIAL", "Path could not send full amount." },
|
||||
|
||||
{ tecUNFUNDED, "tecUNFUNDED", "One of _ADD, _OFFER, or _SEND. Deprecated." },
|
||||
{ tecUNFUNDED_ADD, "tecUNFUNDED_ADD", "Insufficient XRP balance for WalletAdd." },
|
||||
{ tecUNFUNDED_OFFER, "tecUNFUNDED_OFFER", "Insufficient balance to fund created offer." },
|
||||
{ tecUNFUNDED_PAYMENT, "tecUNFUNDED_PAYMENT", "Insufficient XRP balance to send." },
|
||||
|
||||
{ tefFAILURE, "tefFAILURE", "Failed to apply." },
|
||||
{ tefALREADY, "tefALREADY", "The exact transaction was already in this ledger." },
|
||||
{ tefBAD_ADD_AUTH, "tefBAD_ADD_AUTH", "Not authorized to add account." },
|
||||
{ tefBAD_AUTH, "tefBAD_AUTH", "Transaction's public key is not authorized." },
|
||||
{ tefBAD_CLAIM_ID, "tefBAD_CLAIM_ID", "Malformed: Bad claim id." },
|
||||
{ tefBAD_GEN_AUTH, "tefBAD_GEN_AUTH", "Not authorized to claim generator." },
|
||||
{ tefBAD_LEDGER, "tefBAD_LEDGER", "Ledger in unexpected state." },
|
||||
{ tefCLAIMED, "tefCLAIMED", "Can not claim a previously claimed account." },
|
||||
{ tefCREATED, "tefCREATED", "Can't add an already created account." },
|
||||
{ tefDST_TAG_NEEDED, "tefDST_TAG_NEEDED", "Destination tag required." },
|
||||
{ tefEXCEPTION, "tefEXCEPTION", "Unexpected program state." },
|
||||
{ tefGEN_IN_USE, "tefGEN_IN_USE", "Generator already in use." },
|
||||
{ tefINTERNAL, "tefINTERNAL", "Internal error." },
|
||||
{ tefNO_AUTH_REQUIRED, "tefNO_AUTH_REQUIRED", "Auth is not required." },
|
||||
{ tefPAST_SEQ, "tefPAST_SEQ", "This sequence number has already past." },
|
||||
|
||||
{ telLOCAL_ERROR, "telLOCAL_ERROR", "Local failure." },
|
||||
{ telBAD_DOMAIN, "telBAD_DOMAIN", "Domain too long." },
|
||||
{ telBAD_PATH_COUNT, "telBAD_PATH_COUNT", "Malformed: Too many paths." },
|
||||
{ telBAD_PUBLIC_KEY, "telBAD_PUBLIC_KEY", "Public key too long." },
|
||||
{ telFAILED_PROCESSING, "telFAILED_PROCESSING", "Failed to correctly process transaction." },
|
||||
{ telINSUF_FEE_P, "telINSUF_FEE_P", "Fee insufficient." },
|
||||
{ telNO_DST_PARTIAL, "telNO_DST_PARTIAL", "Partial payment to create account not allowed." },
|
||||
|
||||
{ temMALFORMED, "temMALFORMED", "Malformed transaction." },
|
||||
{ temBAD_AMOUNT, "temBAD_AMOUNT", "Can only send positive amounts." },
|
||||
{ temBAD_AUTH_MASTER, "temBAD_AUTH_MASTER", "Auth for unclaimed account needs correct master key." },
|
||||
{ temBAD_CURRENCY, "temBAD_CURRENCY", "Malformed: Bad currency." },
|
||||
{ temBAD_FEE, "temBAD_FEE", "Invalid fee, negative or not XRP." },
|
||||
{ temBAD_EXPIRATION, "temBAD_EXPIRATION", "Malformed: Bad expiration." },
|
||||
{ temBAD_ISSUER, "temBAD_ISSUER", "Malformed: Bad issuer." },
|
||||
{ temBAD_LIMIT, "temBAD_LIMIT", "Limits must be non-negative." },
|
||||
{ temBAD_OFFER, "temBAD_OFFER", "Malformed: Bad offer." },
|
||||
{ temBAD_PATH, "temBAD_PATH", "Malformed: Bad path." },
|
||||
{ temBAD_PATH_LOOP, "temBAD_PATH_LOOP", "Malformed: Loop in path." },
|
||||
{ temBAD_PUBLISH, "temBAD_PUBLISH", "Malformed: Bad publish." },
|
||||
{ temBAD_SIGNATURE, "temBAD_SIGNATURE", "Malformed: Bad signature." },
|
||||
{ temBAD_SRC_ACCOUNT, "temBAD_SRC_ACCOUNT", "Malformed: Bad source account." },
|
||||
{ temBAD_TRANSFER_RATE, "temBAD_TRANSFER_RATE", "Malformed: Transfer rate must be >= 1.0" },
|
||||
{ temBAD_SEQUENCE, "temBAD_SEQUENCE", "Malformed: Sequence is not in the past." },
|
||||
{ temBAD_SEND_XRP_LIMIT, "temBAD_SEND_XRP_LIMIT", "Malformed: Limit quality is not allowed for XRP to XRP." },
|
||||
{ temBAD_SEND_XRP_MAX, "temBAD_SEND_XRP_MAX", "Malformed: Send max is not allowed for XRP to XRP." },
|
||||
{ temBAD_SEND_XRP_NO_DIRECT, "temBAD_SEND_XRP_NO_DIRECT", "Malformed: No Ripple direct is not allowed for XRP to XRP." },
|
||||
{ temBAD_SEND_XRP_PARTIAL, "temBAD_SEND_XRP_PARTIAL", "Malformed: Partial payment is not allowed for XRP to XRP." },
|
||||
{ temBAD_SEND_XRP_PATHS, "temBAD_SEND_XRP_PATHS", "Malformed: Paths are not allowed for XRP to XRP." },
|
||||
{ temDST_IS_SRC, "temDST_IS_SRC", "Destination may not be source." },
|
||||
{ temDST_NEEDED, "temDST_NEEDED", "Destination not specified." },
|
||||
{ temINVALID, "temINVALID", "The transaction is ill-formed." },
|
||||
{ temINVALID_FLAG, "temINVALID_FLAG", "The transaction has an invalid flag." },
|
||||
{ temREDUNDANT, "temREDUNDANT", "Sends same currency to self." },
|
||||
{ temREDUNDANT_SEND_MAX, "temREDUNDANT_SEND_MAX", "Send max is redundant." },
|
||||
{ temRIPPLE_EMPTY, "temRIPPLE_EMPTY", "PathSet with no paths." },
|
||||
{ temUNCERTAIN, "temUNCERTAIN", "In process of determining result. Never returned." },
|
||||
{ temUNKNOWN, "temUNKNOWN", "The transactions requires logic not implemented yet." },
|
||||
|
||||
{ terRETRY, "terRETRY", "Retry transaction." },
|
||||
{ terFUNDS_SPENT, "terFUNDS_SPENT", "Can't set password, password set funds already spent." },
|
||||
{ terINSUF_FEE_B, "terINSUF_FEE_B", "Account balance can't pay fee." },
|
||||
{ terLAST, "terLAST", "Process last." },
|
||||
{ terNO_ACCOUNT, "terNO_ACCOUNT", "The source account does not exist." },
|
||||
{ terNO_AUTH, "terNO_AUTH", "Not authorized to hold IOUs." },
|
||||
{ terNO_LINE, "terNO_LINE", "No such line." },
|
||||
{ terPRE_SEQ, "terPRE_SEQ", "Missing/inapplicable prior transaction." },
|
||||
{ terOWNERS, "terOWNERS", "Non-zero owner count." },
|
||||
|
||||
{ tesSUCCESS, "tesSUCCESS", "The transaction was applied." },
|
||||
};
|
||||
|
||||
int iIndex = NUMBER(transResultInfoA);
|
||||
|
||||
while (iIndex-- && transResultInfoA[iIndex].terCode != terCode)
|
||||
;
|
||||
|
||||
if (iIndex >= 0)
|
||||
{
|
||||
strToken = transResultInfoA[iIndex].cpToken;
|
||||
strHuman = transResultInfoA[iIndex].cpHuman;
|
||||
}
|
||||
|
||||
return iIndex >= 0;
|
||||
}
|
||||
|
||||
std::string transToken(TER terCode)
|
||||
{
|
||||
std::string strToken;
|
||||
std::string strHuman;
|
||||
|
||||
return transResultInfo(terCode, strToken, strHuman) ? strToken : "-";
|
||||
}
|
||||
|
||||
std::string transHuman(TER terCode)
|
||||
{
|
||||
std::string strToken;
|
||||
std::string strHuman;
|
||||
|
||||
return transResultInfo(terCode, strToken, strHuman) ? strHuman : "-";
|
||||
}
|
||||
|
||||
// vim:ts=4
|
||||
@@ -1,153 +0,0 @@
|
||||
#ifndef _TRANSACTION_ERR_
|
||||
#define _TRANSACTION_ERR_
|
||||
|
||||
#include <string>
|
||||
|
||||
enum TER // aka TransactionEngineResult
|
||||
{
|
||||
// Note: Range is stable. Exact numbers are currently unstable. Use tokens.
|
||||
|
||||
// -399 .. -300: L Local error (transaction fee inadequate, exceeds local limit)
|
||||
// Only valid during non-consensus processing.
|
||||
// Implications:
|
||||
// - Not forwarded
|
||||
// - No fee check
|
||||
telLOCAL_ERROR = -399,
|
||||
telBAD_DOMAIN,
|
||||
telBAD_PATH_COUNT,
|
||||
telBAD_PUBLIC_KEY,
|
||||
telFAILED_PROCESSING,
|
||||
telINSUF_FEE_P,
|
||||
telNO_DST_PARTIAL,
|
||||
|
||||
// -299 .. -200: M Malformed (bad signature)
|
||||
// Causes:
|
||||
// - Transaction corrupt.
|
||||
// Implications:
|
||||
// - Not applied
|
||||
// - Not forwarded
|
||||
// - Reject
|
||||
// - Can not succeed in any imagined ledger.
|
||||
temMALFORMED = -299,
|
||||
temBAD_AMOUNT,
|
||||
temBAD_AUTH_MASTER,
|
||||
temBAD_CURRENCY,
|
||||
temBAD_FEE,
|
||||
temBAD_EXPIRATION,
|
||||
temBAD_ISSUER,
|
||||
temBAD_LIMIT,
|
||||
temBAD_OFFER,
|
||||
temBAD_PATH,
|
||||
temBAD_PATH_LOOP,
|
||||
temBAD_PUBLISH,
|
||||
temBAD_TRANSFER_RATE,
|
||||
temBAD_SEND_XRP_LIMIT,
|
||||
temBAD_SEND_XRP_MAX,
|
||||
temBAD_SEND_XRP_NO_DIRECT,
|
||||
temBAD_SEND_XRP_PARTIAL,
|
||||
temBAD_SEND_XRP_PATHS,
|
||||
temBAD_SIGNATURE,
|
||||
temBAD_SRC_ACCOUNT,
|
||||
temBAD_SEQUENCE,
|
||||
temDST_IS_SRC,
|
||||
temDST_NEEDED,
|
||||
temINVALID,
|
||||
temINVALID_FLAG,
|
||||
temREDUNDANT,
|
||||
temREDUNDANT_SEND_MAX,
|
||||
temRIPPLE_EMPTY,
|
||||
temUNCERTAIN, // An intermediate result used internally, should never be returned.
|
||||
temUNKNOWN,
|
||||
|
||||
// -199 .. -100: F Failure (sequence number previously used)
|
||||
// Causes:
|
||||
// - Transaction cannot succeed because of ledger state.
|
||||
// - Unexpected ledger state.
|
||||
// - C++ exception.
|
||||
// Implications:
|
||||
// - Not applied
|
||||
// - Not forwarded
|
||||
// - Could succeed in an imagined ledger.
|
||||
tefFAILURE = -199,
|
||||
tefALREADY,
|
||||
tefBAD_ADD_AUTH,
|
||||
tefBAD_AUTH,
|
||||
tefBAD_CLAIM_ID,
|
||||
tefBAD_GEN_AUTH,
|
||||
tefBAD_LEDGER,
|
||||
tefCLAIMED,
|
||||
tefCREATED,
|
||||
tefDST_TAG_NEEDED,
|
||||
tefEXCEPTION,
|
||||
tefGEN_IN_USE,
|
||||
tefINTERNAL,
|
||||
tefNO_AUTH_REQUIRED, // Can't set auth if auth is not required.
|
||||
tefPAST_SEQ,
|
||||
|
||||
// -99 .. -1: R Retry (sequence too high, no funds for txn fee, originating account non-existent)
|
||||
// Causes:
|
||||
// - Prior application of another, possibly non-existant, another transaction could allow this transaction to succeed.
|
||||
// Implications:
|
||||
// - Not applied
|
||||
// - Not forwarded
|
||||
// - Might succeed later
|
||||
// - Hold
|
||||
// - Makes hole in sequence which jams transactions.
|
||||
terRETRY = -99,
|
||||
terFUNDS_SPENT, // This is a free transaction, therefore don't burden network.
|
||||
terINSUF_FEE_B, // Can't pay fee, therefore don't burden network.
|
||||
terNO_ACCOUNT, // Can't pay fee, therefore don't burden network.
|
||||
terNO_AUTH, // Not authorized to hold IOUs.
|
||||
terNO_LINE, // Internal flag.
|
||||
terOWNERS, // Can't succeed with non-zero owner count.
|
||||
terPRE_SEQ, // Can't pay fee, no point in forwarding, therefore don't burden network.
|
||||
terLAST, // Process after all other transactions
|
||||
|
||||
// 0: S Success (success)
|
||||
// Causes:
|
||||
// - Success.
|
||||
// Implications:
|
||||
// - Applied
|
||||
// - Forwarded
|
||||
tesSUCCESS = 0,
|
||||
|
||||
// 100 .. 129 C Claim fee only (ripple transaction with no good paths, pay to non-existent account, no path)
|
||||
// Causes:
|
||||
// - Success, but does not achieve optimal result.
|
||||
// - Invalid transaction or no effect, but claim fee to use the sequence number.
|
||||
// Implications:
|
||||
// - Applied
|
||||
// - Forwarded
|
||||
// Only allowed as a return code of appliedTransaction when !tapRetry. Otherwise, treated as terRETRY.
|
||||
//
|
||||
// DO NOT CHANGE THESE NUMBERS: They appear in ledger meta data.
|
||||
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.
|
||||
};
|
||||
|
||||
#define isTelLocal(x) ((x) >= telLOCAL_ERROR && (x) < temMALFORMED)
|
||||
#define isTemMalformed(x) ((x) >= temMALFORMED && (x) < tefFAILURE)
|
||||
#define isTefFailure(x) ((x) >= tefFAILURE && (x) < terRETRY)
|
||||
#define isTerRetry(x) ((x) >= terRETRY && (x) < tesSUCCESS)
|
||||
#define isTesSuccess(x) ((x) == tesSUCCESS)
|
||||
#define isTecClaim(x) ((x) >= tecCLAIM)
|
||||
|
||||
bool transResultInfo(TER terCode, std::string& strToken, std::string& strHuman);
|
||||
std::string transToken(TER terCode);
|
||||
std::string transHuman(TER terCode);
|
||||
|
||||
#endif
|
||||
// vim:ts=4
|
||||
@@ -1,4 +1,6 @@
|
||||
var extend = require('extend');
|
||||
'use strict';
|
||||
|
||||
var extend = require('extend');
|
||||
var UInt160 = require('./uint160').UInt160;
|
||||
var utils = require('./utils');
|
||||
var Float = require('./ieee754').Float;
|
||||
@@ -16,8 +18,7 @@ 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);
|
||||
|
||||
@@ -32,25 +33,37 @@ Currency.HEX_CURRENCY_BAD = '0000000000000000000000005852500000000000';
|
||||
* Examples:
|
||||
*
|
||||
* USD => currency
|
||||
* USD - Dollar => currency with optional full currency name
|
||||
* XAU (-0.5%pa) => XAU with 0.5% effective demurrage rate per year
|
||||
* 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
|
||||
* 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
|
||||
* 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:
|
||||
* 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)
|
||||
* ([a-zA-Z]{3}|[0-9]{3}) // either 3 letter alphabetic currency-code or 3
|
||||
* digit numeric currency-code. See ISO 4217
|
||||
* (\s*-\s*[- \w]+) // optional full currency name following the dash
|
||||
* after currency code, full currency code can
|
||||
* contain letters, numbers and dashes
|
||||
* (\s*\(-?\d+\.?\d*%pa\))? // optional demurrage rate, has optional - and
|
||||
* . notation (-0.5%pa)
|
||||
* \s*$ // end with any amount of whitespace
|
||||
*
|
||||
*/
|
||||
Currency.prototype.human_RE = /^\s*([a-zA-Z0-9]{3})(\s*-\s*[- \w]+)?(\s*\(-?\d+\.?\d*%pa\))?\s*$/;
|
||||
|
||||
/*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);
|
||||
@@ -58,39 +71,65 @@ Currency.from_json = function(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) {
|
||||
this._value = NaN;
|
||||
|
||||
switch (typeof j) {
|
||||
case 'string':
|
||||
if (j instanceof Currency) {
|
||||
this._value = j.copyTo({})._value;
|
||||
this._update();
|
||||
return this;
|
||||
}
|
||||
|
||||
// if an empty string is given, fall back to XRP
|
||||
switch (typeof j) {
|
||||
case 'number':
|
||||
if (!isNaN(j)) {
|
||||
this.parse_number(j);
|
||||
}
|
||||
break;
|
||||
case 'string':
|
||||
if (!j || j === '0') {
|
||||
this.parse_hex(shouldInterpretXrpAsIou ? Currency.HEX_CURRENCY_BAD : Currency.HEX_ZERO);
|
||||
// Empty string or XRP
|
||||
this.parse_hex(shouldInterpretXrpAsIou
|
||||
? Currency.HEX_CURRENCY_BAD
|
||||
: Currency.HEX_ZERO);
|
||||
break;
|
||||
}
|
||||
|
||||
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 = String(j).match(this.human_RE);
|
||||
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);
|
||||
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
|
||||
// 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] || '';
|
||||
|
||||
@@ -117,25 +156,28 @@ Currency.prototype.parse_json = function(j, shouldInterpretXrpAsIou) {
|
||||
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 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
|
||||
// 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 interestEfold = secondsPerYear / Math.log(1 + percentage / 100);
|
||||
var bytes = Float.toIEEE754Double(interestEfold);
|
||||
|
||||
for (var i=0; i<=bytes.length; i++) {
|
||||
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
|
||||
// the last 4 bytes are reserved for future use, so we won't fill
|
||||
// those
|
||||
|
||||
} else {
|
||||
currencyData[12] = currencyCode.charCodeAt(0) & 0xff;
|
||||
@@ -144,21 +186,6 @@ Currency.prototype.parse_json = function(j, shouldInterpretXrpAsIou) {
|
||||
}
|
||||
|
||||
this.parse_bytes(currencyData);
|
||||
} else {
|
||||
this.parse_hex(j);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'number':
|
||||
if (!isNaN(j)) {
|
||||
this.parse_number(j);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'object':
|
||||
if (j instanceof Currency) {
|
||||
this._value = j.copyTo({})._value;
|
||||
this._update();
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -166,7 +193,6 @@ Currency.prototype.parse_json = function(j, shouldInterpretXrpAsIou) {
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
Currency.prototype.parse_human = function(j) {
|
||||
return this.parse_json(j);
|
||||
};
|
||||
@@ -176,6 +202,7 @@ Currency.prototype.parse_human = function(j) {
|
||||
*
|
||||
* You should never need to call this.
|
||||
*/
|
||||
|
||||
Currency.prototype._update = function() {
|
||||
var bytes = this.to_bytes();
|
||||
|
||||
@@ -183,7 +210,7 @@ Currency.prototype._update = function() {
|
||||
var isZeroExceptInStandardPositions = true;
|
||||
|
||||
if (!bytes) {
|
||||
return 'XRP';
|
||||
return;
|
||||
}
|
||||
|
||||
this._native = false;
|
||||
@@ -192,8 +219,9 @@ Currency.prototype._update = function() {
|
||||
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) {
|
||||
@@ -201,7 +229,7 @@ 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';
|
||||
}
|
||||
@@ -215,8 +243,8 @@ Currency.prototype._update = function() {
|
||||
this._type = 1;
|
||||
this._interest_start = (bytes[4] << 24) +
|
||||
(bytes[5] << 16) +
|
||||
(bytes[6] << 8) +
|
||||
(bytes[7] );
|
||||
(bytes[6] << 8) +
|
||||
(bytes[7]);
|
||||
this._interest_period = Float.fromIEEE754Double(bytes.slice(8, 16));
|
||||
}
|
||||
};
|
||||
@@ -230,7 +258,8 @@ Currency.prototype.parse_bytes = function(byte_array) {
|
||||
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) {
|
||||
@@ -260,20 +289,25 @@ Currency.prototype.is_native = function() {
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 && !isNaN(this._interest_start) && !isNaN(this._interest_period);
|
||||
return this._type === 1
|
||||
&& !isNaN(this._interest_start)
|
||||
&& !isNaN(this._interest_period);
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param referenceDate - number of seconds since the Ripple Epoch (0:00 on January 1, 2000 UTC)
|
||||
* used to calculate the interest over provided interval
|
||||
* pass in one years worth of seconds to ge the yearly interest
|
||||
* @returns {number} - interest for provided interval, can be negative for demurred currencies
|
||||
* @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, decimals) {
|
||||
Currency.prototype.get_interest_at = function(referenceDate) {
|
||||
if (!this.has_interest()) {
|
||||
return 0;
|
||||
}
|
||||
@@ -288,18 +322,20 @@ Currency.prototype.get_interest_at = function(referenceDate, decimals) {
|
||||
}
|
||||
|
||||
// calculate interest by e-fold number
|
||||
return Math.exp((referenceDate - this._interest_start) / this._interest_period);
|
||||
return Math.exp((referenceDate - this._interest_start)
|
||||
/ this._interest_period);
|
||||
};
|
||||
|
||||
Currency.prototype.get_interest_percentage_at = function(referenceDate, decimals) {
|
||||
Currency.prototype.get_interest_percentage_at
|
||||
= function(referenceDate, decimals) {
|
||||
var interest = this.get_interest_at(referenceDate, decimals);
|
||||
|
||||
// convert to percentage
|
||||
var interest = (interest*100)-100;
|
||||
var decimalMultiplier = decimals ? Math.pow(10,decimals) : 100;
|
||||
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;
|
||||
return Math.round(interest * decimalMultiplier) / decimalMultiplier;
|
||||
};
|
||||
|
||||
// XXX Currently we inherit UInt.prototype.is_valid, which is mostly fine.
|
||||
@@ -307,9 +343,9 @@ Currency.prototype.get_interest_percentage_at = function(referenceDate, decimals
|
||||
// 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(opts) {
|
||||
if (!this.is_valid()) {
|
||||
@@ -317,28 +353,35 @@ Currency.prototype.to_json = function(opts) {
|
||||
return 'XRP';
|
||||
}
|
||||
|
||||
var opts = opts || {};
|
||||
if (!opts) {
|
||||
opts = {};
|
||||
}
|
||||
|
||||
var currency;
|
||||
var fullName = opts && opts.full_name ? ' - ' + opts.full_name : '';
|
||||
opts.show_interest = opts.show_interest !== void(0) ? opts.show_interest : this.has_interest();
|
||||
opts.show_interest = opts.show_interest !== undefined
|
||||
? opts.show_interest
|
||||
: this.has_interest();
|
||||
|
||||
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 : void(0);
|
||||
var interestPercentage = this.has_interest() ? this.get_interest_percentage_at(this._interest_start + 3600 * 24 * 365, decimals) : 0;
|
||||
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.
|
||||
// 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;
|
||||
}
|
||||
@@ -357,5 +400,3 @@ Currency.prototype.get_iso = function() {
|
||||
};
|
||||
|
||||
exports.Currency = Currency;
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
68
src/index.js
Normal file
68
src/index.js
Normal file
@@ -0,0 +1,68 @@
|
||||
'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.Message = require('./message').Message;
|
||||
exports.binformat = require('./binformat');
|
||||
exports.utils = require('./utils');
|
||||
exports.Server = require('./server').Server;
|
||||
exports.Ledger = require('./ledger').Ledger;
|
||||
exports.TransactionQueue = require('./transactionqueue').TransactionQueue;
|
||||
exports.RangeSet = require('./rangeset').RangeSet;
|
||||
exports.convertBase = require('./baseconverter');
|
||||
|
||||
exports._test = {
|
||||
Log: require('./log'),
|
||||
PathFind: require('./pathfind').PathFind,
|
||||
TransactionManager: require('./transactionmanager').TransactionManager
|
||||
};
|
||||
|
||||
// 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
|
||||
// any time without warning.
|
||||
//
|
||||
// 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.Wallet = require('ripple-wallet-generator')({sjcl: exports.sjcl});
|
||||
exports.types = require('./serializedtypes');
|
||||
|
||||
// camelCase to under_scored API conversion
|
||||
function attachUnderscored(name) {
|
||||
const o = exports[name];
|
||||
|
||||
Object.keys(o.prototype).forEach(function(key) {
|
||||
const UPPERCASE = /([A-Z]{1})[a-z]+/g;
|
||||
|
||||
if (!UPPERCASE.test(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const underscored = key.replace(UPPERCASE, function(c) {
|
||||
return '_' + c.toLowerCase();
|
||||
});
|
||||
|
||||
o.prototype[underscored] = o.prototype[key];
|
||||
});
|
||||
}
|
||||
|
||||
['Remote',
|
||||
'Request',
|
||||
'Transaction',
|
||||
'Account',
|
||||
'Server'
|
||||
].forEach(attachUnderscored);
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
1
src/js
Submodule
1
src/js
Submodule
Submodule src/js added at 16dde36fa2
1210
src/js/jsbn/jsbn.js
1210
src/js/jsbn/jsbn.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,59 +0,0 @@
|
||||
var async = require('async');
|
||||
var superagent = require('superagent');
|
||||
var RippleTxt = require('./rippletxt').RippleTxt;
|
||||
|
||||
var AuthInfo = { };
|
||||
|
||||
AuthInfo._getRippleTxt = function(domain, callback) {
|
||||
RippleTxt.get(domain, callback);
|
||||
};
|
||||
|
||||
AuthInfo._getUser = function(url, callback) {
|
||||
superagent.get(url, callback);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get auth info for a given username
|
||||
*
|
||||
* @param {string} domain - Domain which hosts the user's info
|
||||
* @param {string} username - Username who's info we are retreiving
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
AuthInfo.get = function(domain, username, callback) {
|
||||
var self = this;
|
||||
username = username.toLowerCase();
|
||||
|
||||
function getRippleTxt(callback) {
|
||||
self._getRippleTxt(domain, function(err, txt) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (!txt.authinfo_url) {
|
||||
return callback(new Error('Authentication is not supported on ' + domain));
|
||||
}
|
||||
|
||||
var url = Array.isArray(txt.authinfo_url) ? txt.authinfo_url[0] : txt.authinfo_url;
|
||||
|
||||
url += '?domain=' + domain + '&username=' + username;
|
||||
|
||||
callback(null, url);
|
||||
});
|
||||
};
|
||||
|
||||
function getUser(url, callback) {
|
||||
self._getUser(url, function(err, res) {
|
||||
if (err || res.error) {
|
||||
callback(new Error('Authentication info server unreachable'));
|
||||
} else {
|
||||
callback(null, res.body);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
async.waterfall([ getRippleTxt, getUser ], callback);
|
||||
};
|
||||
|
||||
exports.AuthInfo = AuthInfo;
|
||||
@@ -1,169 +0,0 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var utils = require('./utils');
|
||||
var extend = require('extend');
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
var Base = {};
|
||||
|
||||
var alphabets = Base.alphabets = {
|
||||
ripple: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz',
|
||||
tipple: 'RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz',
|
||||
bitcoin: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
||||
};
|
||||
|
||||
extend(Base, {
|
||||
VER_NONE : 1,
|
||||
VER_NODE_PUBLIC : 28,
|
||||
VER_NODE_PRIVATE : 32,
|
||||
VER_ACCOUNT_ID : 0,
|
||||
VER_ACCOUNT_PUBLIC : 35,
|
||||
VER_ACCOUNT_PRIVATE : 34,
|
||||
VER_FAMILY_GENERATOR : 41,
|
||||
VER_FAMILY_SEED : 33
|
||||
});
|
||||
|
||||
function sha256(bytes) {
|
||||
return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
|
||||
};
|
||||
|
||||
function sha256hash(bytes) {
|
||||
return sha256(sha256(bytes));
|
||||
};
|
||||
|
||||
// --> input: big-endian array of bytes.
|
||||
// <-- string at least as long as input.
|
||||
Base.encode = function(input, alpha) {
|
||||
var alphabet = alphabets[alpha || 'ripple'];
|
||||
var bi_base = new BigInteger(String(alphabet.length));
|
||||
var bi_q = 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('');
|
||||
};
|
||||
|
||||
// --> input: String
|
||||
// <-- array of bytes or undefined.
|
||||
Base.decode = function(input, alpha) {
|
||||
if (typeof input !== 'string') {
|
||||
return void(0);
|
||||
}
|
||||
|
||||
var alphabet = alphabets[alpha || 'ripple'];
|
||||
var bi_base = new BigInteger(String(alphabet.length));
|
||||
var bi_value = 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
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;
|
||||
};
|
||||
|
||||
// --> input: Array
|
||||
// <-- String
|
||||
Base.encode_check = function(version, input, alphabet) {
|
||||
var buffer = [].concat(version, input);
|
||||
var check = sha256(sha256(buffer)).slice(0, 4);
|
||||
|
||||
return Base.encode([].concat(buffer, check), alphabet);
|
||||
};
|
||||
|
||||
// --> input : String
|
||||
// <-- NaN || BigInteger
|
||||
Base.decode_check = function(version, input, alphabet) {
|
||||
var buffer = Base.decode(input, alphabet);
|
||||
|
||||
if (!buffer || buffer.length < 5) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// Single valid version
|
||||
if (typeof version === 'number' && buffer[0] !== version) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// Multiple allowed versions
|
||||
if (Array.isArray(version)) {
|
||||
var match = false;
|
||||
|
||||
for (var i=0, l=version.length; i<l; i++) {
|
||||
match |= version[i] === buffer[0];
|
||||
}
|
||||
|
||||
if (!match) {
|
||||
return NaN;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Base.verify_checksum(buffer)) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
// We'll use the version byte to add a leading zero, this ensures JSBN doesn't
|
||||
// intrepret the value as a negative number
|
||||
buffer[0] = 0;
|
||||
|
||||
return new BigInteger(buffer.slice(0, -4), 256);
|
||||
};
|
||||
|
||||
exports.Base = Base;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,10 +0,0 @@
|
||||
// This object serves as a singleton to store config options
|
||||
|
||||
var extend = require('extend');
|
||||
|
||||
var config = module.exports = {
|
||||
load: function (newOpts) {
|
||||
extend(config, newOpts);
|
||||
return config;
|
||||
}
|
||||
};
|
||||
@@ -1,333 +0,0 @@
|
||||
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,59 +0,0 @@
|
||||
/**
|
||||
* IEEE 754 floating-point.
|
||||
*
|
||||
* Supports single- or double-precision
|
||||
*/
|
||||
var Float = exports.Float = {};
|
||||
|
||||
var allZeros = /^0+$/;
|
||||
var allOnes = /^1+$/;
|
||||
|
||||
Float.fromBytes = function(bytes) {
|
||||
// Render in binary. Hackish.
|
||||
var b = '';
|
||||
|
||||
for (var i = 0, n = bytes.length; i < n; i++) {
|
||||
var bits = (bytes[i] & 0xff).toString(2);
|
||||
|
||||
while (bits.length < 8) {
|
||||
bits = '0' + bits;
|
||||
}
|
||||
|
||||
b += bits;
|
||||
}
|
||||
|
||||
// Determine configuration. This could have all been precomputed but it is fast enough.
|
||||
var exponentBits = bytes.length === 4 ? 4 : 11;
|
||||
var mantissaBits = (bytes.length * 8) - exponentBits - 1;
|
||||
var bias = Math.pow(2, exponentBits - 1) - 1;
|
||||
var minExponent = 1 - bias - mantissaBits;
|
||||
|
||||
// Break up the binary representation into its pieces for easier processing.
|
||||
var s = b[0];
|
||||
var e = b.substring(1, exponentBits + 1);
|
||||
var m = b.substring(exponentBits + 1);
|
||||
|
||||
var value = 0;
|
||||
var multiplier = (s === '0' ? 1 : -1);
|
||||
|
||||
if (allZeros.test(e)) {
|
||||
// Zero or denormalized
|
||||
if (!allZeros.test(m)) {
|
||||
value = parseInt(m, 2) * Math.pow(2, minExponent);
|
||||
}
|
||||
} else if (allOnes.test(e)) {
|
||||
// Infinity or NaN
|
||||
if (allZeros.test(m)) {
|
||||
value = Infinity;
|
||||
} else {
|
||||
value = NaN;
|
||||
}
|
||||
} else {
|
||||
// Normalized
|
||||
var exponent = parseInt(e, 2) - bias;
|
||||
var mantissa = parseInt(m, 2);
|
||||
value = (1 + (mantissa * Math.pow(2, -mantissaBits))) * Math.pow(2, exponent);
|
||||
}
|
||||
|
||||
return value * multiplier;
|
||||
};
|
||||
@@ -1,60 +0,0 @@
|
||||
exports.Remote = require('./remote').Remote;
|
||||
exports.Request = require('./request').Request;
|
||||
exports.Amount = require('./amount').Amount;
|
||||
exports.Account = require('./account').Account;
|
||||
exports.Transaction = require('./transaction').Transaction;
|
||||
exports.Currency = require('./currency').Currency;
|
||||
exports.Base = require('./base').Base;
|
||||
exports.UInt160 = require('./uint160').UInt160;
|
||||
exports.UInt256 = require('./uint256').UInt256;
|
||||
exports.Seed = require('./seed').Seed;
|
||||
exports.Meta = require('./meta').Meta;
|
||||
exports.SerializedObject = require('./serializedobject').SerializedObject;
|
||||
exports.RippleError = require('./rippleerror').RippleError;
|
||||
exports.Message = require('./message').Message;
|
||||
exports.VaultClient = require('./vaultclient').VaultClient;
|
||||
exports.AuthInfo = require('./authinfo').AuthInfo;
|
||||
exports.RippleTxt = require('./rippletxt').RippleTxt;
|
||||
exports.binformat = require('./binformat');
|
||||
exports.utils = require('./utils');
|
||||
exports.Server = require('./server').Server;
|
||||
exports.Wallet = require('./wallet');
|
||||
|
||||
// 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
|
||||
// any time without warning.
|
||||
//
|
||||
// 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.config = require('./config');
|
||||
|
||||
// camelCase to under_scored API conversion
|
||||
function attachUnderscored(c) {
|
||||
var o = exports[c];
|
||||
|
||||
Object.keys(o.prototype).forEach(function(key) {
|
||||
var UPPERCASE = /([A-Z]{1})[a-z]+/g;
|
||||
|
||||
if (!UPPERCASE.test(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var underscored = key.replace(UPPERCASE, function(c) {
|
||||
return '_' + c.toLowerCase();
|
||||
});
|
||||
|
||||
o.prototype[underscored] = o.prototype[key];
|
||||
});
|
||||
};
|
||||
|
||||
[ 'Remote',
|
||||
'Request',
|
||||
'Transaction',
|
||||
'Account',
|
||||
'Server'
|
||||
].forEach(attachUnderscored);
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* Logging functionality for ripple-lib and any applications built on it.
|
||||
*/
|
||||
function Log(namespace) {
|
||||
if (!namespace) {
|
||||
this._namespace = [];
|
||||
} else if (Array.isArray(namespace)) {
|
||||
this._namespace = namespace;
|
||||
} else {
|
||||
this._namespace = [''+namespace];
|
||||
}
|
||||
|
||||
this._prefix = this._namespace.concat(['']).join(': ');
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a sub-logger.
|
||||
*
|
||||
* You can have a hierarchy of loggers.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* var log = require('ripple').log.sub('server');
|
||||
*
|
||||
* log.info('connection successful');
|
||||
* // prints: 'server: connection successful'
|
||||
*/
|
||||
Log.prototype.sub = function(namespace) {
|
||||
var subNamespace = this._namespace.slice();
|
||||
|
||||
if (namespace && typeof namespace === 'string') {
|
||||
subNamespace.push(namespace);
|
||||
}
|
||||
|
||||
var subLogger = new Log(subNamespace);
|
||||
subLogger._setParent(this);
|
||||
return subLogger;
|
||||
};
|
||||
|
||||
Log.prototype._setParent = function(parentLogger) {
|
||||
this._parent = parentLogger;
|
||||
};
|
||||
|
||||
Log.makeLevel = function(level) {
|
||||
return function() {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args[0] = this._prefix + args[0];
|
||||
Log.engine.logObject.apply(Log, args);
|
||||
};
|
||||
};
|
||||
|
||||
Log.prototype.debug = Log.makeLevel(1);
|
||||
Log.prototype.info = Log.makeLevel(2);
|
||||
Log.prototype.warn = Log.makeLevel(3);
|
||||
Log.prototype.error = Log.makeLevel(4);
|
||||
|
||||
/**
|
||||
* Basic logging connector.
|
||||
*
|
||||
* This engine has no formatting and works with the most basic of 'console.log'
|
||||
* implementations. This is the logging engine used in Node.js.
|
||||
*/
|
||||
var BasicLogEngine = {
|
||||
logObject: function logObject(msg) {
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
|
||||
args = args.map(function(arg) {
|
||||
return JSON.stringify(arg, null, 2);
|
||||
});
|
||||
|
||||
args.unshift(msg);
|
||||
args.unshift('[' + new Date().toISOString() + ']');
|
||||
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Null logging connector.
|
||||
*
|
||||
* This engine simply swallows all messages. Used when console.log is not
|
||||
* available.
|
||||
*/
|
||||
var NullLogEngine = {
|
||||
logObject: function() {}
|
||||
};
|
||||
|
||||
Log.engine = NullLogEngine;
|
||||
|
||||
if (console && console.log) {
|
||||
Log.engine = BasicLogEngine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a root logger as our main export.
|
||||
*
|
||||
* This means you can use the logger easily on the fly:
|
||||
* ripple.log.debug('My object is', myObj);
|
||||
*/
|
||||
module.exports = new Log();
|
||||
|
||||
/**
|
||||
* This is the logger for ripple-lib internally.
|
||||
*/
|
||||
module.exports.internal = module.exports.sub();
|
||||
|
||||
/**
|
||||
* Expose the class as well.
|
||||
*/
|
||||
module.exports.Log = Log;
|
||||
@@ -1,31 +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);
|
||||
args.unshift('[' + new Date().toISOString() + ']');
|
||||
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
};
|
||||
|
||||
if (window.console && window.console.log) {
|
||||
exports.Log.engine = InteractiveLogEngine;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,133 +0,0 @@
|
||||
var request = require('superagent');
|
||||
var Currency = require('./currency').Currency;
|
||||
|
||||
var RippleTxt = {
|
||||
txts : { }
|
||||
};
|
||||
|
||||
RippleTxt.urlTemplates = [
|
||||
'https://{{domain}}/ripple.txt',
|
||||
'https://www.{{domain}}/ripple.txt',
|
||||
'https://ripple.{{domain}}/ripple.txt',
|
||||
'http://{{domain}}/ripple.txt',
|
||||
'http://www.{{domain}}/ripple.txt',
|
||||
'http://ripple.{{domain}}/ripple.txt'
|
||||
];
|
||||
|
||||
/**
|
||||
* Gets the ripple.txt file for the given domain
|
||||
* @param {string} domain - Domain to retrieve file from
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
RippleTxt.get = function(domain, fn) {
|
||||
var self = this;
|
||||
|
||||
if (self.txts[domain]) {
|
||||
return fn(null, self.txts[domain]);
|
||||
}
|
||||
|
||||
;(function nextUrl(i) {
|
||||
var url = RippleTxt.urlTemplates[i];
|
||||
|
||||
if (!url) {
|
||||
return fn(new Error('No ripple.txt found'));
|
||||
}
|
||||
|
||||
url = url.replace('{{domain}}', domain);
|
||||
|
||||
request.get(url, function(err, resp) {
|
||||
if (err || !resp.text) {
|
||||
return nextUrl(++i);
|
||||
}
|
||||
|
||||
var sections = self.parse(resp.text);
|
||||
self.txts[domain] = sections;
|
||||
|
||||
fn(null, sections);
|
||||
});
|
||||
})(0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a ripple.txt file
|
||||
* @param {string} txt - Unparsed ripple.txt data
|
||||
*/
|
||||
|
||||
RippleTxt.parse = function(txt) {
|
||||
var currentSection = '';
|
||||
var sections = { };
|
||||
|
||||
txt = txt.replace(/\r?\n/g, '\n').split('\n');
|
||||
|
||||
for (var i = 0, l = txt.length; i < l; i++) {
|
||||
var line = txt[i];
|
||||
|
||||
if (!line.length || line[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line[0] === '[' && line[line.length - 1] === ']') {
|
||||
currentSection = line.slice(1, line.length - 1);
|
||||
sections[currentSection] = [];
|
||||
} else {
|
||||
line = line.replace(/^\s+|\s+$/g, '');
|
||||
if (sections[currentSection]) {
|
||||
sections[currentSection].push(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sections;
|
||||
};
|
||||
|
||||
/**
|
||||
* extractDomain
|
||||
* attempt to extract the domain from a given url
|
||||
* returns the url if unsuccessful
|
||||
* @param {Object} url
|
||||
*/
|
||||
|
||||
RippleTxt.extractDomain = function (url) {
|
||||
match = /[^.]*\.[^.]{2,3}(?:\.[^.]{2,3})?([^.\?][^\?.]+?)?$/.exec(url);
|
||||
return match && match[0] ? match[0] : url;
|
||||
};
|
||||
|
||||
/**
|
||||
* getCurrencies
|
||||
* returns domain, issuer account and currency object
|
||||
* for each currency found in the domain's ripple.txt file
|
||||
* @param {Object} domain
|
||||
* @param {Object} fn
|
||||
*/
|
||||
|
||||
RippleTxt.getCurrencies = function(domain, fn) {
|
||||
domain = RippleTxt.extractDomain(domain);
|
||||
this.get(domain, function(err, txt) {
|
||||
if (err) {
|
||||
return fn(err);
|
||||
}
|
||||
|
||||
if (err || !txt.currencies || !txt.accounts) {
|
||||
return fn(null, []);
|
||||
}
|
||||
|
||||
//NOTE: this won't be accurate if there are
|
||||
//multiple issuer accounts with different
|
||||
//currencies associated with each.
|
||||
var issuer = txt.accounts[0];
|
||||
var currencies = [];
|
||||
|
||||
txt.currencies.forEach(function(currency) {
|
||||
currencies.push({
|
||||
issuer : issuer,
|
||||
currency : Currency.from_json(currency),
|
||||
domain : domain
|
||||
});
|
||||
});
|
||||
|
||||
fn(null, currencies);
|
||||
});
|
||||
};
|
||||
|
||||
exports.RippleTxt = RippleTxt;
|
||||
@@ -1,755 +0,0 @@
|
||||
/**
|
||||
* Type definitions for binary format.
|
||||
*
|
||||
* This file should not be included directly. Instead, find the format you're
|
||||
* trying to parse or serialize in binformat.js and pass that to
|
||||
* SerializedObject.parse() or SerializedObject.serialize().
|
||||
*/
|
||||
|
||||
var assert = require('assert');
|
||||
var extend = require('extend');
|
||||
var binformat = require('./binformat');
|
||||
var utils = require('./utils');
|
||||
var sjcl = utils.sjcl;
|
||||
|
||||
var UInt128 = require('./uint128').UInt128;
|
||||
var UInt160 = require('./uint160').UInt160;
|
||||
var UInt256 = require('./uint256').UInt256;
|
||||
var Base = require('./base').Base;
|
||||
|
||||
var amount = require('./amount');
|
||||
var Amount = amount.Amount;
|
||||
var Currency = amount.Currency;
|
||||
|
||||
// Shortcuts
|
||||
var hex = sjcl.codec.hex;
|
||||
var bytes = sjcl.codec.bytes;
|
||||
|
||||
var BigInteger = utils.jsbn.BigInteger;
|
||||
|
||||
|
||||
var SerializedType = function (methods) {
|
||||
extend(this, methods);
|
||||
};
|
||||
|
||||
function isNumber(val) {
|
||||
return typeof val === 'number' && isFinite(val);
|
||||
};
|
||||
|
||||
function isString(val) {
|
||||
return typeof val === 'string';
|
||||
};
|
||||
|
||||
function isHexInt64String(val) {
|
||||
return isString(val) && /^[0-9A-F]{0,16}$/i.test(val);
|
||||
};
|
||||
|
||||
function isCurrencyString(val) {
|
||||
return isString(val) && /^[A-Z0-9]{3}$/.test(val);
|
||||
};
|
||||
|
||||
function isBigInteger(val) {
|
||||
return val instanceof BigInteger;
|
||||
};
|
||||
|
||||
function serialize_hex(so, hexData, noLength) {
|
||||
var byteData = bytes.fromBits(hex.toBits(hexData));
|
||||
if (!noLength) {
|
||||
SerializedType.serialize_varint(so, byteData.length);
|
||||
}
|
||||
so.append(byteData);
|
||||
};
|
||||
|
||||
/**
|
||||
* parses bytes as hex
|
||||
*/
|
||||
function convert_bytes_to_hex (byte_array) {
|
||||
return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(byte_array)).toUpperCase();
|
||||
};
|
||||
|
||||
SerializedType.serialize_varint = function (so, val) {
|
||||
if (val < 0) {
|
||||
throw new Error('Variable integers are unsigned.');
|
||||
}
|
||||
|
||||
if (val <= 192) {
|
||||
so.append([val]);
|
||||
} else if (val <= 12480) {
|
||||
val -= 193;
|
||||
so.append([193 + (val >>> 8), val & 0xff]);
|
||||
} else if (val <= 918744) {
|
||||
val -= 12481;
|
||||
so.append([ 241 + (val >>> 16), val >>> 8 & 0xff, val & 0xff ]);
|
||||
} else {
|
||||
throw new Error('Variable integer overflow.');
|
||||
}
|
||||
};
|
||||
|
||||
SerializedType.prototype.parse_varint = function (so) {
|
||||
var b1 = so.read(1)[0], b2, b3;
|
||||
var result;
|
||||
|
||||
if (b1 > 254) {
|
||||
throw new Error('Invalid varint length indicator');
|
||||
}
|
||||
|
||||
if (b1 <= 192) {
|
||||
result = b1;
|
||||
} else if (b1 <= 240) {
|
||||
b2 = so.read(1)[0];
|
||||
result = 193 + (b1 - 193) * 256 + b2;
|
||||
} else if (b1 <= 254) {
|
||||
b2 = so.read(1)[0];
|
||||
b3 = so.read(1)[0];
|
||||
result = 12481 + (b1 - 241) * 65536 + b2 * 256 + b3;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// In the following, we assume that the inputs are in the proper range. Is this correct?
|
||||
// Helper functions for 1-, 2-, and 4-byte integers.
|
||||
|
||||
/**
|
||||
* Convert an integer value into an array of bytes.
|
||||
*
|
||||
* The result is appended to the serialized object ('so').
|
||||
*/
|
||||
function append_byte_array(so, val, bytes) {
|
||||
if (!isNumber(val)) {
|
||||
throw new Error('Value is not a number', bytes);
|
||||
}
|
||||
|
||||
if (val < 0 || val >= Math.pow(256, bytes)) {
|
||||
throw new Error('Value out of bounds');
|
||||
}
|
||||
|
||||
var newBytes = [ ];
|
||||
|
||||
for (var i=0; i<bytes; i++) {
|
||||
newBytes.unshift(val >>> (i * 8) & 0xff);
|
||||
}
|
||||
|
||||
so.append(newBytes);
|
||||
};
|
||||
|
||||
// Convert a certain number of bytes from the serialized object ('so') into an integer.
|
||||
function readAndSum(so, bytes) {
|
||||
var sum = 0;
|
||||
|
||||
if (bytes > 4) {
|
||||
throw new Error('This function only supports up to four bytes.');
|
||||
}
|
||||
|
||||
for (var i=0; i<bytes; i++) {
|
||||
var byte = so.read(1)[0];
|
||||
sum += (byte << (8 * (bytes - i - 1)));
|
||||
}
|
||||
|
||||
// Convert to unsigned integer
|
||||
return sum >>> 0;
|
||||
};
|
||||
|
||||
var STInt8 = exports.Int8 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
append_byte_array(so, val, 1);
|
||||
},
|
||||
parse: function (so) {
|
||||
return readAndSum(so, 1);
|
||||
}
|
||||
});
|
||||
|
||||
STInt8.id = 16;
|
||||
|
||||
var STInt16 = exports.Int16 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
append_byte_array(so, val, 2);
|
||||
},
|
||||
parse: function (so) {
|
||||
return readAndSum(so, 2);
|
||||
}
|
||||
});
|
||||
|
||||
STInt16.id = 1;
|
||||
|
||||
var STInt32 = exports.Int32 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
append_byte_array(so, val, 4);
|
||||
},
|
||||
parse: function (so) {
|
||||
return readAndSum(so, 4);
|
||||
}
|
||||
});
|
||||
|
||||
STInt32.id = 2;
|
||||
|
||||
var STInt64 = exports.Int64 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var bigNumObject;
|
||||
|
||||
if (isNumber(val)) {
|
||||
val = Math.floor(val);
|
||||
if (val < 0) {
|
||||
throw new Error('Negative value for unsigned Int64 is invalid.');
|
||||
}
|
||||
bigNumObject = new BigInteger(String(val), 10);
|
||||
} else if (isString(val)) {
|
||||
if (!isHexInt64String(val)) {
|
||||
throw new Error('Not a valid hex Int64.');
|
||||
}
|
||||
bigNumObject = new BigInteger(val, 16);
|
||||
} else if (isBigInteger(val)) {
|
||||
if (val.compareTo(BigInteger.ZERO) < 0) {
|
||||
throw new Error('Negative value for unsigned Int64 is invalid.');
|
||||
}
|
||||
bigNumObject = val;
|
||||
} else {
|
||||
throw new Error('Invalid type for Int64');
|
||||
}
|
||||
|
||||
var hex = bigNumObject.toString(16);
|
||||
|
||||
if (hex.length > 16) {
|
||||
throw new Error('Int64 is too large');
|
||||
}
|
||||
|
||||
while (hex.length < 16) {
|
||||
hex = '0' + hex;
|
||||
}
|
||||
|
||||
serialize_hex(so, hex, true); //noLength = true
|
||||
},
|
||||
parse: function (so) {
|
||||
var bytes = so.read(8);
|
||||
// We need to add a 0, so if the high bit is set it won't think it's a
|
||||
// pessimistic numeric fraek. What doth lief?
|
||||
var result = new BigInteger([0].concat(bytes), 256);
|
||||
assert(result instanceof BigInteger);
|
||||
return result;
|
||||
}
|
||||
});
|
||||
|
||||
STInt64.id = 3;
|
||||
|
||||
var STHash128 = exports.Hash128 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var hash = UInt128.from_json(val);
|
||||
if (!hash.is_valid()) {
|
||||
throw new Error('Invalid Hash128');
|
||||
}
|
||||
serialize_hex(so, hash.to_hex(), true); //noLength = true
|
||||
},
|
||||
parse: function (so) {
|
||||
return UInt128.from_bytes(so.read(16));
|
||||
}
|
||||
});
|
||||
|
||||
STHash128.id = 4;
|
||||
|
||||
var STHash256 = exports.Hash256 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var hash = UInt256.from_json(val);
|
||||
if (!hash.is_valid()) {
|
||||
throw new Error('Invalid Hash256');
|
||||
}
|
||||
serialize_hex(so, hash.to_hex(), true); //noLength = true
|
||||
},
|
||||
parse: function (so) {
|
||||
return UInt256.from_bytes(so.read(32));
|
||||
}
|
||||
});
|
||||
|
||||
STHash256.id = 5;
|
||||
|
||||
var STHash160 = exports.Hash160 = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var hash = UInt160.from_json(val);
|
||||
if (!hash.is_valid()) {
|
||||
throw new Error('Invalid Hash160');
|
||||
}
|
||||
serialize_hex(so, hash.to_hex(), true); //noLength = true
|
||||
},
|
||||
parse: function (so) {
|
||||
return UInt160.from_bytes(so.read(20));
|
||||
}
|
||||
});
|
||||
|
||||
STHash160.id = 17;
|
||||
|
||||
// Internal
|
||||
var STCurrency = new SerializedType({
|
||||
serialize: function (so, val, xrp_as_ascii) {
|
||||
var currencyData = val.to_bytes();
|
||||
|
||||
if (!currencyData) {
|
||||
throw new Error('Tried to serialize invalid/unimplemented currency type.');
|
||||
}
|
||||
|
||||
so.append(currencyData);
|
||||
},
|
||||
parse: function (so) {
|
||||
var bytes = so.read(20);
|
||||
var currency = Currency.from_bytes(bytes);
|
||||
// XXX Disabled check. Theoretically, the Currency class should support any
|
||||
// UInt160 value and consider it valid. But it doesn't, so for the
|
||||
// deserialization to be usable, we need to allow invalid results for now.
|
||||
//if (!currency.is_valid()) {
|
||||
// throw new Error('Invalid currency: '+convert_bytes_to_hex(bytes));
|
||||
//}
|
||||
return currency;
|
||||
}
|
||||
});
|
||||
|
||||
var STAmount = exports.Amount = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var amount = Amount.from_json(val);
|
||||
if (!amount.is_valid()) {
|
||||
throw new Error('Not a valid Amount object.');
|
||||
}
|
||||
|
||||
// Amount (64-bit integer)
|
||||
var valueBytes = utils.arraySet(8, 0);
|
||||
|
||||
if (amount.is_native()) {
|
||||
var valueHex = amount._value.toString(16);
|
||||
|
||||
// Enforce correct length (64 bits)
|
||||
if (valueHex.length > 16) {
|
||||
throw new Error('Value out of bounds');
|
||||
}
|
||||
|
||||
while (valueHex.length < 16) {
|
||||
valueHex = '0' + valueHex;
|
||||
}
|
||||
|
||||
valueBytes = bytes.fromBits(hex.toBits(valueHex));
|
||||
// Clear most significant two bits - these bits should already be 0 if
|
||||
// Amount enforces the range correctly, but we'll clear them anyway just
|
||||
// so this code can make certain guarantees about the encoded value.
|
||||
valueBytes[0] &= 0x3f;
|
||||
|
||||
if (!amount.is_negative()) {
|
||||
valueBytes[0] |= 0x40;
|
||||
}
|
||||
} else {
|
||||
var hi = 0, lo = 0;
|
||||
|
||||
// First bit: non-native
|
||||
hi |= 1 << 31;
|
||||
|
||||
if (!amount.is_zero()) {
|
||||
// Second bit: non-negative?
|
||||
if (!amount.is_negative()) {
|
||||
hi |= 1 << 30;
|
||||
}
|
||||
|
||||
// Next eight bits: offset/exponent
|
||||
hi |= ((97 + amount._offset) & 0xff) << 22;
|
||||
// Remaining 54 bits: mantissa
|
||||
hi |= amount._value.shiftRight(32).intValue() & 0x3fffff;
|
||||
lo = amount._value.intValue() & 0xffffffff;
|
||||
}
|
||||
|
||||
valueBytes = sjcl.codec.bytes.fromBits([hi, lo]);
|
||||
}
|
||||
|
||||
so.append(valueBytes);
|
||||
|
||||
if (!amount.is_native()) {
|
||||
// Currency (160-bit hash)
|
||||
var currency = amount.currency();
|
||||
STCurrency.serialize(so, currency, true);
|
||||
|
||||
// Issuer (160-bit hash)
|
||||
so.append(amount.issuer().to_bytes());
|
||||
}
|
||||
},
|
||||
parse: function (so) {
|
||||
var amount = new Amount();
|
||||
var value_bytes = so.read(8);
|
||||
var is_zero = !(value_bytes[0] & 0x7f);
|
||||
|
||||
for (var i=1; i<8; i++) {
|
||||
is_zero = is_zero && !value_bytes[i];
|
||||
}
|
||||
|
||||
if (value_bytes[0] & 0x80) {
|
||||
//non-native
|
||||
var currency = STCurrency.parse(so);
|
||||
var issuer_bytes = so.read(20);
|
||||
var issuer = UInt160.from_bytes(issuer_bytes);
|
||||
issuer.set_version(Base.VER_ACCOUNT_ID);
|
||||
var offset = ((value_bytes[0] & 0x3f) << 2) + (value_bytes[1] >>> 6) - 97;
|
||||
var mantissa_bytes = value_bytes.slice(1);
|
||||
mantissa_bytes[0] &= 0x3f;
|
||||
var value = new BigInteger(mantissa_bytes, 256);
|
||||
|
||||
if (value.equals(BigInteger.ZERO) && !is_zero ) {
|
||||
throw new Error('Invalid zero representation');
|
||||
}
|
||||
|
||||
amount._value = value;
|
||||
amount._offset = offset;
|
||||
amount._currency = currency;
|
||||
amount._issuer = issuer;
|
||||
amount._is_native = false;
|
||||
} else {
|
||||
//native
|
||||
var integer_bytes = value_bytes.slice();
|
||||
integer_bytes[0] &= 0x3f;
|
||||
amount._value = new BigInteger(integer_bytes, 256);
|
||||
amount._is_native = true;
|
||||
}
|
||||
amount._is_negative = !is_zero && !(value_bytes[0] & 0x40);
|
||||
return amount;
|
||||
}
|
||||
});
|
||||
|
||||
STAmount.id = 6;
|
||||
|
||||
var STVL = exports.VariableLength = exports.VL = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
if (typeof val === 'string') {
|
||||
serialize_hex(so, val);
|
||||
} else {
|
||||
throw new Error('Unknown datatype.');
|
||||
}
|
||||
},
|
||||
parse: function (so) {
|
||||
var len = this.parse_varint(so);
|
||||
return convert_bytes_to_hex(so.read(len));
|
||||
}
|
||||
});
|
||||
|
||||
STVL.id = 7;
|
||||
|
||||
var STAccount = exports.Account = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
var account = UInt160.from_json(val);
|
||||
if (!account.is_valid()) {
|
||||
throw new Error('Invalid account!');
|
||||
}
|
||||
serialize_hex(so, account.to_hex());
|
||||
},
|
||||
parse: function (so) {
|
||||
var len = this.parse_varint(so);
|
||||
|
||||
if (len !== 20) {
|
||||
throw new Error('Non-standard-length account ID');
|
||||
}
|
||||
|
||||
var result = UInt160.from_bytes(so.read(len));
|
||||
result.set_version(Base.VER_ACCOUNT_ID);
|
||||
|
||||
//console.log('PARSED 160:', result.to_json());
|
||||
if (false && !result.is_valid()) {
|
||||
throw new Error('Invalid Account');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
});
|
||||
|
||||
STAccount.id = 8;
|
||||
|
||||
var STPathSet = exports.PathSet = new SerializedType({
|
||||
typeBoundary: 0xff,
|
||||
typeEnd: 0x00,
|
||||
typeAccount: 0x01,
|
||||
typeCurrency: 0x10,
|
||||
typeIssuer: 0x20,
|
||||
serialize: function (so, val) {
|
||||
for (var i=0, l=val.length; i<l; i++) {
|
||||
// Boundary
|
||||
if (i) {
|
||||
STInt8.serialize(so, this.typeBoundary);
|
||||
}
|
||||
|
||||
for (var j=0, l2=val[i].length; j<l2; j++) {
|
||||
var entry = val[i][j];
|
||||
//if (entry.hasOwnProperty('_value')) {entry = entry._value;}
|
||||
var type = 0;
|
||||
|
||||
if (entry.account) {
|
||||
type |= this.typeAccount;
|
||||
}
|
||||
if (entry.currency) {
|
||||
type |= this.typeCurrency;
|
||||
}
|
||||
if (entry.issuer) {
|
||||
type |= this.typeIssuer;
|
||||
}
|
||||
|
||||
STInt8.serialize(so, type);
|
||||
|
||||
if (entry.account) {
|
||||
so.append(UInt160.from_json(entry.account).to_bytes());
|
||||
}
|
||||
|
||||
if (entry.currency) {
|
||||
var currency = Currency.from_json(entry.currency, entry.non_native);
|
||||
STCurrency.serialize(so, currency);
|
||||
}
|
||||
|
||||
if (entry.issuer) {
|
||||
so.append(UInt160.from_json(entry.issuer).to_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
STInt8.serialize(so, this.typeEnd);
|
||||
},
|
||||
parse: function (so) {
|
||||
// should return a list of lists:
|
||||
/*
|
||||
[
|
||||
[entry, entry],
|
||||
[entry, entry, entry],
|
||||
[entry],
|
||||
[]
|
||||
]
|
||||
|
||||
each entry has one or more of the following attributes: amount, currency, issuer.
|
||||
*/
|
||||
|
||||
var path_list = [];
|
||||
var current_path = [];
|
||||
var tag_byte;
|
||||
|
||||
while ((tag_byte = so.read(1)[0]) !== this.typeEnd) {
|
||||
//TODO: try/catch this loop, and catch when we run out of data without reaching the end of the data structure.
|
||||
//Now determine: is this an end, boundary, or entry-begin-tag?
|
||||
//console.log('Tag byte:', tag_byte);
|
||||
if (tag_byte === this.typeBoundary) {
|
||||
//console.log('Boundary');
|
||||
if (current_path) { //close the current path, if there is one,
|
||||
path_list.push(current_path);
|
||||
}
|
||||
current_path = [ ]; //and start a new one.
|
||||
continue;
|
||||
}
|
||||
|
||||
//It's an entry-begin tag.
|
||||
//console.log('It's an entry-begin tag.');
|
||||
var entry = {};
|
||||
|
||||
if (tag_byte & this.typeAccount) {
|
||||
//console.log('entry.account');
|
||||
/*var bta = so.read(20);
|
||||
console.log('BTA:', bta);*/
|
||||
entry.account = STHash160.parse(so);
|
||||
entry.account.set_version(Base.VER_ACCOUNT_ID);
|
||||
}
|
||||
if (tag_byte & this.typeCurrency) {
|
||||
//console.log('entry.currency');
|
||||
entry.currency = STCurrency.parse(so);
|
||||
if (entry.currency.to_json() === 'XRP' && !entry.currency.is_native()) {
|
||||
entry.non_native = true;
|
||||
}
|
||||
}
|
||||
if (tag_byte & this.typeIssuer) {
|
||||
//console.log('entry.issuer');
|
||||
entry.issuer = STHash160.parse(so);
|
||||
// Enable and set correct type of base-58 encoding
|
||||
entry.issuer.set_version(Base.VER_ACCOUNT_ID);
|
||||
//console.log('DONE WITH ISSUER!');
|
||||
}
|
||||
|
||||
if (entry.account || entry.currency || entry.issuer) {
|
||||
current_path.push(entry);
|
||||
} else {
|
||||
throw new Error('Invalid path entry'); //It must have at least something in it.
|
||||
}
|
||||
}
|
||||
|
||||
if (current_path) {
|
||||
//close the current path, if there is one,
|
||||
path_list.push(current_path);
|
||||
}
|
||||
|
||||
return path_list;
|
||||
}
|
||||
});
|
||||
|
||||
STPathSet.id = 18;
|
||||
|
||||
var STVector256 = exports.Vector256 = new SerializedType({
|
||||
serialize: function (so, val) { //Assume val is an array of STHash256 objects.
|
||||
var length_as_varint = SerializedType.serialize_varint(so, val.length * 32);
|
||||
for (var i=0, l=val.length; i<l; i++) {
|
||||
STHash256.serialize(so, val[i]);
|
||||
}
|
||||
},
|
||||
parse: function (so) {
|
||||
var length = this.parse_varint(so);
|
||||
var output = [];
|
||||
// length is number of bytes not number of Hash256
|
||||
for (var i=0; i<length / 32; i++) {
|
||||
output.push(STHash256.parse(so));
|
||||
}
|
||||
return output;
|
||||
}
|
||||
});
|
||||
|
||||
STVector256.id = 19;
|
||||
|
||||
exports.serialize = exports.serialize_whatever = serialize;
|
||||
|
||||
function serialize(so, field_name, value) {
|
||||
//so: a byte-stream to serialize into.
|
||||
//field_name: a string for the field name ('LedgerEntryType' etc.)
|
||||
//value: the value of that field.
|
||||
var field_coordinates = binformat.fieldsInverseMap[field_name];
|
||||
var type_bits = field_coordinates[0];
|
||||
var field_bits = field_coordinates[1];
|
||||
var tag_byte = (type_bits < 16 ? type_bits << 4 : 0) | (field_bits < 16 ? field_bits : 0);
|
||||
|
||||
if (field_name === 'LedgerEntryType' && 'string' === typeof value) {
|
||||
value = binformat.ledger[value][0];
|
||||
}
|
||||
|
||||
if (field_name === 'TransactionResult' && 'string' === typeof value) {
|
||||
value = binformat.ter[value];
|
||||
}
|
||||
|
||||
STInt8.serialize(so, tag_byte);
|
||||
|
||||
if (type_bits >= 16) {
|
||||
STInt8.serialize(so, type_bits);
|
||||
}
|
||||
|
||||
if (field_bits >= 16) {
|
||||
STInt8.serialize(so, field_bits);
|
||||
}
|
||||
|
||||
// Get the serializer class (ST...) for a field based on the type bits.
|
||||
var serialized_object_type = exports[binformat.types[type_bits]];
|
||||
//do something with val[keys] and val[keys[i]];
|
||||
|
||||
try {
|
||||
serialized_object_type.serialize(so, value);
|
||||
} catch (e) {
|
||||
e.message += ' (' + field_name + ')';
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
//Take the serialized object, figure out what type/field it is, and return the parsing of that.
|
||||
exports.parse = exports.parse_whatever = parse;
|
||||
|
||||
function parse(so) {
|
||||
var tag_byte = so.read(1)[0];
|
||||
var type_bits = tag_byte >> 4;
|
||||
|
||||
if (type_bits === 0) {
|
||||
type_bits = so.read(1)[0];
|
||||
}
|
||||
|
||||
// Get the parser class (ST...) for a field based on the type bits.
|
||||
var type = exports[binformat.types[type_bits]];
|
||||
|
||||
assert(type, 'Unknown type - header byte is 0x' + tag_byte.toString(16));
|
||||
|
||||
var field_bits = tag_byte & 0x0f;
|
||||
var field_name = (field_bits === 0)
|
||||
? field_name = binformat.fields[type_bits][so.read(1)[0]]
|
||||
: field_name = binformat.fields[type_bits][field_bits];
|
||||
|
||||
assert(field_name, 'Unknown field - header byte is 0x' + tag_byte.toString(16));
|
||||
|
||||
return [ field_name, type.parse(so) ]; //key, value
|
||||
};
|
||||
|
||||
function sort_fields(keys) {
|
||||
function sort_field_compare(a, b) {
|
||||
var a_field_coordinates = binformat.fieldsInverseMap[a];
|
||||
var a_type_bits = a_field_coordinates[0];
|
||||
var a_field_bits = a_field_coordinates[1];
|
||||
var b_field_coordinates = binformat.fieldsInverseMap[b];
|
||||
var b_type_bits = b_field_coordinates[0];
|
||||
var b_field_bits = b_field_coordinates[1];
|
||||
|
||||
// Sort by type id first, then by field id
|
||||
return a_type_bits !== b_type_bits ? a_type_bits - b_type_bits : a_field_bits - b_field_bits;
|
||||
};
|
||||
|
||||
return keys.sort(sort_field_compare);
|
||||
}
|
||||
|
||||
var STObject = exports.Object = new SerializedType({
|
||||
serialize: function (so, val, no_marker) {
|
||||
var keys = Object.keys(val);
|
||||
|
||||
// Ignore lowercase field names - they're non-serializable fields by
|
||||
// convention.
|
||||
keys = keys.filter(function (key) {
|
||||
return key[0] !== key[0].toLowerCase();
|
||||
});
|
||||
|
||||
keys.forEach(function (key) {
|
||||
if (typeof binformat.fieldsInverseMap[key] === 'undefined') {
|
||||
throw new Error('JSON contains unknown field: "' + key + '"');
|
||||
}
|
||||
});
|
||||
|
||||
// Sort fields
|
||||
keys = sort_fields(keys);
|
||||
|
||||
for (var i=0; i<keys.length; i++) {
|
||||
serialize(so, keys[i], val[keys[i]]);
|
||||
}
|
||||
|
||||
if (!no_marker) {
|
||||
//Object ending marker
|
||||
STInt8.serialize(so, 0xe1);
|
||||
}
|
||||
},
|
||||
|
||||
parse: function (so) {
|
||||
var output = {};
|
||||
while (so.peek(1)[0] !== 0xe1) {
|
||||
var keyval = parse(so);
|
||||
output[keyval[0]] = keyval[1];
|
||||
}
|
||||
so.read(1);
|
||||
return output;
|
||||
}
|
||||
});
|
||||
|
||||
STObject.id = 14;
|
||||
|
||||
var STArray = exports.Array = new SerializedType({
|
||||
serialize: function (so, val) {
|
||||
for (var i=0, l=val.length; i<l; i++) {
|
||||
var keys = Object.keys(val[i]);
|
||||
|
||||
if (keys.length !== 1) {
|
||||
throw Error('Cannot serialize an array containing non-single-key objects');
|
||||
}
|
||||
|
||||
var field_name = keys[0];
|
||||
var value = val[i][field_name];
|
||||
serialize(so, field_name, value);
|
||||
}
|
||||
|
||||
//Array ending marker
|
||||
STInt8.serialize(so, 0xf1);
|
||||
},
|
||||
|
||||
parse: function (so) {
|
||||
var output = [ ];
|
||||
|
||||
while (so.peek(1)[0] !== 0xf1) {
|
||||
var keyval = parse(so);
|
||||
var obj = { };
|
||||
obj[keyval[0]] = keyval[1];
|
||||
output.push(obj);
|
||||
}
|
||||
|
||||
so.read(1);
|
||||
|
||||
return output;
|
||||
}
|
||||
});
|
||||
|
||||
STArray.id = 15;
|
||||
@@ -1,203 +0,0 @@
|
||||
var Crypt = require('./crypt').Crypt;
|
||||
var Message = require('./message').Message;
|
||||
var parser = require("url");
|
||||
var querystring = require('querystring');
|
||||
var extend = require("extend");
|
||||
|
||||
var SignedRequest = function (config) {
|
||||
// XXX Constructor should be generalized and constructing from an Angular.js
|
||||
// $http config should be a SignedRequest.from... utility method.
|
||||
this.config = extend(true, {}, config);
|
||||
if (!this.config.data) this.config.data = {};
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Create a string from request parameters that
|
||||
* will be used to sign a request
|
||||
* @param {Object} parsed - parsed url
|
||||
* @param {Object} date
|
||||
* @param {Object} mechanism - type of signing
|
||||
*/
|
||||
SignedRequest.prototype.getStringToSign = function (parsed, date, mechanism) {
|
||||
// XXX This method doesn't handle signing GET requests correctly. The data
|
||||
// field will be merged into the search string, not the request body.
|
||||
|
||||
// Sort the properties of the JSON object into canonical form
|
||||
var canonicalData = JSON.stringify(copyObjectWithSortedKeys(this.config.data));
|
||||
|
||||
// Canonical request using Amazon's v4 signature format
|
||||
// See: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
|
||||
var canonicalRequest = [
|
||||
this.config.method || 'GET',
|
||||
parsed.pathname || '',
|
||||
parsed.search || '',
|
||||
// XXX Headers signing not supported
|
||||
'',
|
||||
'',
|
||||
Crypt.hashSha512(canonicalData).toLowerCase()
|
||||
].join('\n');
|
||||
|
||||
// String to sign inspired by Amazon's v4 signature format
|
||||
// See: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
|
||||
//
|
||||
// We don't have a credential scope, so we skip it.
|
||||
//
|
||||
// But that modifies the format, so the format ID is RIPPLE1, instead of AWS4.
|
||||
return [
|
||||
mechanism,
|
||||
date,
|
||||
Crypt.hashSha512(canonicalRequest).toLowerCase()
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
//prepare for signing
|
||||
function copyObjectWithSortedKeys(object) {
|
||||
if (isPlainObject(object)) {
|
||||
var newObj = {};
|
||||
var keysSorted = Object.keys(object).sort();
|
||||
var key;
|
||||
for (var i in keysSorted) {
|
||||
key = keysSorted[i];
|
||||
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
||||
newObj[key] = copyObjectWithSortedKeys(object[key]);
|
||||
}
|
||||
}
|
||||
return newObj;
|
||||
} else if (Array.isArray(object)) {
|
||||
return object.map(copyObjectWithSortedKeys);
|
||||
} else {
|
||||
return object;
|
||||
}
|
||||
}
|
||||
|
||||
//from npm extend
|
||||
function isPlainObject(obj) {
|
||||
var hasOwn = Object.prototype.hasOwnProperty;
|
||||
var toString = Object.prototype.toString;
|
||||
|
||||
if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)
|
||||
return false;
|
||||
|
||||
var has_own_constructor = hasOwn.call(obj, 'constructor');
|
||||
var has_is_property_of_method = hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
|
||||
// Not own constructor property must be Object
|
||||
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
|
||||
return false;
|
||||
|
||||
// Own properties are enumerated firstly, so to speed up,
|
||||
// if last one is own, then all properties are own.
|
||||
var key;
|
||||
for ( key in obj ) {}
|
||||
|
||||
return key === undefined || hasOwn.call( obj, key );
|
||||
};
|
||||
|
||||
/**
|
||||
* HMAC signed request
|
||||
* @param {Object} config
|
||||
* @param {Object} auth_secret
|
||||
* @param {Object} blob_id
|
||||
*/
|
||||
SignedRequest.prototype.signHmac = function (auth_secret, blob_id) {
|
||||
var config = extend(true, {}, this.config);
|
||||
|
||||
// Parse URL
|
||||
var parsed = parser.parse(config.url);
|
||||
var date = dateAsIso8601();
|
||||
var signatureType = 'RIPPLE1-HMAC-SHA512';
|
||||
var stringToSign = this.getStringToSign(parsed, date, signatureType);
|
||||
var signature = Crypt.signString(auth_secret, stringToSign);
|
||||
|
||||
var query = querystring.stringify({
|
||||
signature: Crypt.base64ToBase64Url(signature),
|
||||
signature_date: date,
|
||||
signature_blob_id: blob_id,
|
||||
signature_type: signatureType
|
||||
});
|
||||
|
||||
config.url += (parsed.search ? '&' : '?') + query;
|
||||
return config;
|
||||
};
|
||||
|
||||
/**
|
||||
* Asymmetric signed request
|
||||
* @param {Object} config
|
||||
* @param {Object} secretKey
|
||||
* @param {Object} account
|
||||
* @param {Object} blob_id
|
||||
*/
|
||||
SignedRequest.prototype.signAsymmetric = function (secretKey, account, blob_id) {
|
||||
var config = extend(true, {}, this.config);
|
||||
|
||||
// Parse URL
|
||||
var parsed = parser.parse(config.url);
|
||||
var date = dateAsIso8601();
|
||||
var signatureType = 'RIPPLE1-ECDSA-SHA512';
|
||||
var stringToSign = this.getStringToSign(parsed, date, signatureType);
|
||||
var signature = Message.signMessage(stringToSign, secretKey);
|
||||
|
||||
var query = querystring.stringify({
|
||||
signature: Crypt.base64ToBase64Url(signature),
|
||||
signature_date: date,
|
||||
signature_blob_id: blob_id,
|
||||
signature_account: account,
|
||||
signature_type: signatureType
|
||||
});
|
||||
|
||||
config.url += (parsed.search ? '&' : '?') + query;
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
/**
|
||||
* Asymmetric signed request for vault recovery
|
||||
* @param {Object} config
|
||||
* @param {Object} secretKey
|
||||
* @param {Object} username
|
||||
*/
|
||||
SignedRequest.prototype.signAsymmetricRecovery = function (secretKey, username) {
|
||||
var config = extend(true, {}, this.config);
|
||||
|
||||
// Parse URL
|
||||
var parsed = parser.parse(config.url);
|
||||
var date = dateAsIso8601();
|
||||
var signatureType = 'RIPPLE1-ECDSA-SHA512';
|
||||
var stringToSign = this.getStringToSign(parsed, date, signatureType);
|
||||
var signature = Message.signMessage(stringToSign, secretKey);
|
||||
|
||||
var query = querystring.stringify({
|
||||
signature: Crypt.base64ToBase64Url(signature),
|
||||
signature_date: date,
|
||||
signature_username: username,
|
||||
signature_type: signatureType
|
||||
});
|
||||
|
||||
config.url += (parsed.search ? '&' : '?') + query;
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
var dateAsIso8601 = (function () {
|
||||
function pad(n) {
|
||||
return (n < 0 || n > 9 ? "" : "0") + n;
|
||||
}
|
||||
|
||||
return function dateAsIso8601() {
|
||||
var date = new Date();
|
||||
return date.getUTCFullYear() + "-" +
|
||||
pad(date.getUTCMonth() + 1) + "-" +
|
||||
pad(date.getUTCDate()) + "T" +
|
||||
pad(date.getUTCHours()) + ":" +
|
||||
pad(date.getUTCMinutes()) + ":" +
|
||||
pad(date.getUTCSeconds()) + ".000Z";
|
||||
};
|
||||
})();
|
||||
|
||||
// XXX Add methods for verifying requests
|
||||
// SignedRequest.prototype.verifySignatureHmac
|
||||
// SignedRequest.prototype.verifySignatureAsymetric
|
||||
|
||||
exports.SignedRequest = SignedRequest;
|
||||
|
||||
@@ -1,977 +0,0 @@
|
||||
// Transactions
|
||||
//
|
||||
// Construction:
|
||||
// remote.transaction() // Build a transaction object.
|
||||
// .offer_create(...) // Set major parameters.
|
||||
// .set_flags() // Set optional parameters.
|
||||
// .on() // Register for events.
|
||||
// .submit(); // Send to network.
|
||||
//
|
||||
// Events:
|
||||
// 'success' : Transaction submitted without error.
|
||||
// 'error' : Error submitting transaction.
|
||||
// 'proposed' : Advisory proposed status transaction.
|
||||
// - A client should expect 0 to multiple results.
|
||||
// - Might not get back. The remote might just forward the transaction.
|
||||
// - A success could be reverted in final.
|
||||
// - local error: other remotes might like it.
|
||||
// - malformed error: local server thought it was malformed.
|
||||
// - The client should only trust this when talking to a trusted server.
|
||||
// 'final' : Final status of transaction.
|
||||
// - Only expect a final from dishonest servers after a tesSUCCESS or ter*.
|
||||
// 'lost' : Gave up looking for on ledger_closed.
|
||||
// 'pending' : Transaction was not found on ledger_closed.
|
||||
// 'state' : Follow the state of a transaction.
|
||||
// 'client_submitted' - Sent to remote
|
||||
// |- 'remoteError' - Remote rejected transaction.
|
||||
// \- 'client_proposed' - Remote provisionally accepted transaction.
|
||||
// |- 'client_missing' - Transaction has not appeared in ledger as expected.
|
||||
// | |\- 'client_lost' - No longer monitoring missing transaction.
|
||||
// |/
|
||||
// |- 'tesSUCCESS' - Transaction in ledger as expected.
|
||||
// |- 'ter...' - Transaction failed.
|
||||
// \- 'tec...' - Transaction claimed fee only.
|
||||
//
|
||||
// Notes:
|
||||
// - All transactions including those with local and malformed errors may be
|
||||
// forwarded anyway.
|
||||
// - A malicous server can:
|
||||
// - give any proposed result.
|
||||
// - it may declare something correct as incorrect or something incorrect as correct.
|
||||
// - it may not communicate with the rest of the network.
|
||||
// - may or may not forward.
|
||||
//
|
||||
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var util = require('util');
|
||||
var utils = require('./utils');
|
||||
var sjcl = require('./utils').sjcl;
|
||||
var Amount = require('./amount').Amount;
|
||||
var Currency = require('./amount').Currency;
|
||||
var UInt160 = require('./amount').UInt160;
|
||||
var Seed = require('./seed').Seed;
|
||||
var SerializedObject = require('./serializedobject').SerializedObject;
|
||||
var RippleError = require('./rippleerror').RippleError;
|
||||
var hashprefixes = require('./hashprefixes');
|
||||
var config = require('./config');
|
||||
|
||||
function Transaction(remote) {
|
||||
EventEmitter.call(this);
|
||||
|
||||
var self = this;
|
||||
|
||||
var remote = remote || void(0);
|
||||
|
||||
this.remote = remote;
|
||||
|
||||
// Transaction data
|
||||
this.tx_json = { Flags: 0 };
|
||||
|
||||
this._secret = void(0);
|
||||
this._build_path = false;
|
||||
this._maxFee = (typeof remote === 'object') ? this.remote.max_fee : void(0);
|
||||
|
||||
this.state = 'unsubmitted';
|
||||
this.finalized = false;
|
||||
this.previousSigningHash = void(0);
|
||||
|
||||
// Index at which transaction was submitted
|
||||
this.submitIndex = void(0);
|
||||
|
||||
// Canonical signing setting defaults to the Remote's configuration
|
||||
this.canonical = (typeof remote === 'object') ? Boolean(remote.canonical_signing) : true;
|
||||
|
||||
// We aren't clever enough to eschew preventative measures so we keep an array
|
||||
// of all submitted transactionIDs (which can change due to load_factor
|
||||
// effecting the Fee amount). This should be populated with a transactionID
|
||||
// any time it goes on the network
|
||||
this.submittedIDs = [ ];
|
||||
|
||||
this.once('success', function(message) {
|
||||
self.finalize(message);
|
||||
self.setState('validated');
|
||||
self.emit('cleanup', message);
|
||||
});
|
||||
|
||||
this.once('error', function(message) {
|
||||
self.finalize(message);
|
||||
self.setState('failed');
|
||||
self.emit('cleanup', message);
|
||||
});
|
||||
|
||||
this.once('submitted', function() {
|
||||
self.setState('submitted');
|
||||
});
|
||||
|
||||
this.once('proposed', function() {
|
||||
self.setState('pending');
|
||||
});
|
||||
};
|
||||
|
||||
util.inherits(Transaction, EventEmitter);
|
||||
|
||||
// XXX This needs to be determined from the network.
|
||||
Transaction.fee_units = {
|
||||
default: 10
|
||||
};
|
||||
|
||||
Transaction.flags = {
|
||||
// Universal flags can apply to any transaction type
|
||||
Universal: {
|
||||
FullyCanonicalSig: 0x80000000
|
||||
},
|
||||
|
||||
AccountSet: {
|
||||
RequireDestTag: 0x00010000,
|
||||
OptionalDestTag: 0x00020000,
|
||||
RequireAuth: 0x00040000,
|
||||
OptionalAuth: 0x00080000,
|
||||
DisallowXRP: 0x00100000,
|
||||
AllowXRP: 0x00200000
|
||||
},
|
||||
|
||||
TrustSet: {
|
||||
SetAuth: 0x00010000,
|
||||
NoRipple: 0x00020000,
|
||||
SetNoRipple: 0x00020000,
|
||||
ClearNoRipple: 0x00040000,
|
||||
SetFreeze: 0x00100000,
|
||||
ClearFreeze: 0x00200000
|
||||
},
|
||||
|
||||
OfferCreate: {
|
||||
Passive: 0x00010000,
|
||||
ImmediateOrCancel: 0x00020000,
|
||||
FillOrKill: 0x00040000,
|
||||
Sell: 0x00080000
|
||||
},
|
||||
|
||||
Payment: {
|
||||
NoRippleDirect: 0x00010000,
|
||||
PartialPayment: 0x00020000,
|
||||
LimitQuality: 0x00040000
|
||||
}
|
||||
};
|
||||
|
||||
// The following are integer (as opposed to bit) flags
|
||||
// that can be set for particular transactions in the
|
||||
// SetFlag or ClearFlag field
|
||||
Transaction.set_clear_flags = {
|
||||
AccountSet: {
|
||||
asfRequireDest: 1,
|
||||
asfRequireAuth: 2,
|
||||
asfDisallowXRP: 3,
|
||||
asfDisableMaster: 4,
|
||||
asfNoFreeze: 6,
|
||||
asfGlobalFreeze: 7
|
||||
}
|
||||
};
|
||||
|
||||
Transaction.MEMO_TYPES = {
|
||||
};
|
||||
|
||||
Transaction.formats = require('./binformat').tx;
|
||||
|
||||
Transaction.prototype.consts = {
|
||||
telLOCAL_ERROR: -399,
|
||||
temMALFORMED: -299,
|
||||
tefFAILURE: -199,
|
||||
terRETRY: -99,
|
||||
tesSUCCESS: 0,
|
||||
tecCLAIMED: 100
|
||||
};
|
||||
|
||||
Transaction.from_json = function(j) {
|
||||
return (new Transaction()).parseJson(j);
|
||||
};
|
||||
|
||||
Transaction.prototype.parseJson = function(v) {
|
||||
this.tx_json = v;
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTelLocal = function(ter) {
|
||||
return ter >= this.consts.telLOCAL_ERROR && ter < this.consts.temMALFORMED;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTemMalformed = function(ter) {
|
||||
return ter >= this.consts.temMALFORMED && ter < this.consts.tefFAILURE;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTefFailure = function(ter) {
|
||||
return ter >= this.consts.tefFAILURE && ter < this.consts.terRETRY;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTerRetry = function(ter) {
|
||||
return ter >= this.consts.terRETRY && ter < this.consts.tesSUCCESS;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTepSuccess = function(ter) {
|
||||
return ter >= this.consts.tesSUCCESS;
|
||||
};
|
||||
|
||||
Transaction.prototype.isTecClaimed = function(ter) {
|
||||
return ter >= this.consts.tecCLAIMED;
|
||||
};
|
||||
|
||||
Transaction.prototype.isRejected = function(ter) {
|
||||
return this.isTelLocal(ter) || this.isTemMalformed(ter) || this.isTefFailure(ter);
|
||||
};
|
||||
|
||||
Transaction.prototype.setState = function(state) {
|
||||
if (this.state !== state) {
|
||||
this.state = state;
|
||||
this.emit('state', state);
|
||||
this.emit('save');
|
||||
}
|
||||
};
|
||||
|
||||
Transaction.prototype.finalize = function(message) {
|
||||
this.finalized = true;
|
||||
|
||||
if (this.result) {
|
||||
this.result.ledger_index = message.ledger_index;
|
||||
this.result.ledger_hash = message.ledger_hash;
|
||||
} else {
|
||||
this.result = message;
|
||||
this.result.tx_json = this.tx_json;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype._accountSecret = function(account) {
|
||||
return this.remote ? this.remote.secrets[account] : void(0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of fee units this transaction will cost.
|
||||
*
|
||||
* Each Ripple transaction based on its type and makeup costs a certain number
|
||||
* of fee units. The fee units are calculated on a per-server basis based on the
|
||||
* current load on both the network and the server.
|
||||
*
|
||||
* @see https://ripple.com/wiki/Transaction_Fee
|
||||
*
|
||||
* @return {Number} Number of fee units for this transaction.
|
||||
*/
|
||||
|
||||
Transaction.prototype._getFeeUnits =
|
||||
Transaction.prototype.feeUnits = function() {
|
||||
return Transaction.fee_units['default'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Compute median server fee
|
||||
*/
|
||||
|
||||
Transaction.prototype._computeFee = function() {
|
||||
if (!this.remote) {
|
||||
return void(0);
|
||||
}
|
||||
|
||||
var servers = this.remote._servers;
|
||||
var fees = [ ];
|
||||
|
||||
for (var i=0; i<servers.length; i++) {
|
||||
var server = servers[i];
|
||||
if (server._connected) {
|
||||
fees.push(Number(server._computeFee(this)));
|
||||
}
|
||||
}
|
||||
|
||||
switch (fees.length) {
|
||||
case 0: return;
|
||||
case 1: return String(fees[0]);
|
||||
}
|
||||
|
||||
fees.sort(function ascending(a, b) {
|
||||
if (a > b) {
|
||||
return 1;
|
||||
} else if (a < b) {
|
||||
return -1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
var midInd = Math.floor(fees.length / 2);
|
||||
|
||||
var median = fees.length % 2 === 0
|
||||
? Math.floor(0.5 + (fees[midInd] + fees[midInd - 1]) / 2)
|
||||
: fees[midInd];
|
||||
|
||||
return String(median);
|
||||
};
|
||||
|
||||
/**
|
||||
* Attempts to complete the transaction for submission.
|
||||
*
|
||||
* This function seeks to fill out certain fields, such as Fee and
|
||||
* SigningPubKey, which can be determined by the library based on network
|
||||
* information and other fields.
|
||||
*/
|
||||
|
||||
Transaction.prototype.complete = function() {
|
||||
if (this.remote) {
|
||||
if (!this.remote.trusted && !this.remote.local_signing) {
|
||||
this.emit('error', new RippleError('tejServerUntrusted', 'Attempt to give secret to untrusted server'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to auto-fill the secret
|
||||
if (!this._secret && !(this._secret = this._accountSecret(this.tx_json.Account))) {
|
||||
this.emit('error', new RippleError('tejSecretUnknown', 'Missing secret'));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof this.tx_json.SigningPubKey === 'undefined') {
|
||||
try {
|
||||
var seed = Seed.from_json(this._secret);
|
||||
var key = seed.get_key(this.tx_json.Account);
|
||||
this.tx_json.SigningPubKey = key.to_hex_pub();
|
||||
} catch(e) {
|
||||
this.emit('error', new RippleError('tejSecretInvalid', 'Invalid secret'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If the Fee hasn't been set, one needs to be computed by
|
||||
// an assigned server
|
||||
if (this.remote && typeof this.tx_json.Fee === 'undefined') {
|
||||
if (this.remote.local_fee || !this.remote.trusted) {
|
||||
if (!(this.tx_json.Fee = this._computeFee())) {
|
||||
this.emit('error', new RippleError('tejUnconnected'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Number(this.tx_json.Fee) > this._maxFee) {
|
||||
this.emit('error', new RippleError('tejMaxFeeExceeded', 'Max fee exceeded'));
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set canonical flag - this enables canonicalized signature checking
|
||||
if (this.remote && this.remote.local_signing && this.canonical) {
|
||||
this.tx_json.Flags |= Transaction.flags.Universal.FullyCanonicalSig;
|
||||
|
||||
// JavaScript converts operands to 32-bit signed ints before doing bitwise
|
||||
// operations. We need to convert it back to an unsigned int.
|
||||
this.tx_json.Flags = this.tx_json.Flags >>> 0;
|
||||
}
|
||||
|
||||
return this.tx_json;
|
||||
};
|
||||
|
||||
Transaction.prototype.serialize = function() {
|
||||
return SerializedObject.from_json(this.tx_json);
|
||||
};
|
||||
|
||||
Transaction.prototype.signingHash = function() {
|
||||
return this.hash(config.testnet ? 'HASH_TX_SIGN_TESTNET' : 'HASH_TX_SIGN');
|
||||
};
|
||||
|
||||
Transaction.prototype.hash = function(prefix, as_uint256) {
|
||||
if (typeof prefix === 'string') {
|
||||
if (typeof hashprefixes[prefix] === 'undefined') {
|
||||
throw new Error('Unknown hashing prefix requested.');
|
||||
}
|
||||
prefix = hashprefixes[prefix];
|
||||
} else if (!prefix) {
|
||||
prefix = hashprefixes.HASH_TX_ID;
|
||||
}
|
||||
|
||||
var hash = SerializedObject.from_json(this.tx_json).hash(prefix);
|
||||
|
||||
return as_uint256 ? hash : hash.to_hex();
|
||||
};
|
||||
|
||||
Transaction.prototype.sign = function(callback) {
|
||||
var callback = typeof callback === 'function' ? callback : function(){};
|
||||
var seed = Seed.from_json(this._secret);
|
||||
|
||||
var prev_sig = this.tx_json.TxnSignature;
|
||||
delete this.tx_json.TxnSignature;
|
||||
|
||||
var hash = this.signingHash();
|
||||
|
||||
// If the hash is the same, we can re-use the previous signature
|
||||
if (prev_sig && hash === this.previousSigningHash) {
|
||||
this.tx_json.TxnSignature = prev_sig;
|
||||
callback();
|
||||
return this;
|
||||
}
|
||||
|
||||
var key = seed.get_key(this.tx_json.Account);
|
||||
var sig = key.sign(hash, 0);
|
||||
var hex = sjcl.codec.hex.fromBits(sig).toUpperCase();
|
||||
|
||||
this.tx_json.TxnSignature = hex;
|
||||
this.previousSigningHash = hash;
|
||||
|
||||
callback();
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a ID to list of submitted IDs for this transaction
|
||||
*/
|
||||
|
||||
Transaction.prototype.addId = function(hash) {
|
||||
if (this.submittedIDs.indexOf(hash) === -1) {
|
||||
this.submittedIDs.unshift(hash);
|
||||
this.emit('signed', hash);
|
||||
this.emit('save');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Find ID within list of submitted IDs for this transaction
|
||||
*/
|
||||
|
||||
Transaction.prototype.findId = function(cache) {
|
||||
var result;
|
||||
|
||||
for (var i=0; i<this.submittedIDs.length; i++) {
|
||||
var hash = this.submittedIDs[i];
|
||||
if ((result = cache[hash])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
//
|
||||
// Set options for Transactions
|
||||
//
|
||||
|
||||
// --> build: true, to have server blindly construct a path.
|
||||
//
|
||||
// "blindly" because the sender has no idea of the actual cost except that is must be less than send max.
|
||||
Transaction.prototype.buildPath = function(build) {
|
||||
this._build_path = build;
|
||||
return this;
|
||||
};
|
||||
|
||||
// tag should be undefined or a 32 bit integer.
|
||||
// YYY Add range checking for tag.
|
||||
Transaction.prototype.destinationTag = function(tag) {
|
||||
if (tag !== void(0)) {
|
||||
this.tx_json.DestinationTag = tag;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.invoiceID = function(id) {
|
||||
if (typeof id === 'string') {
|
||||
while (id.length < 64) {
|
||||
id += '0';
|
||||
}
|
||||
this.tx_json.InvoiceID = id;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.clientID = function(id) {
|
||||
if (typeof id === 'string') {
|
||||
this._clientID = id;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.lastLedger = function(sequence) {
|
||||
if (typeof sequence === 'number' && isFinite(sequence)) {
|
||||
this._setLastLedger = true;
|
||||
this.tx_json.LastLedgerSequence = sequence;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/*
|
||||
* Set the transaction's proposed fee. No op when fee parameter
|
||||
* is not 0 or a positive number
|
||||
*
|
||||
* @param {Number} fee The proposed fee
|
||||
*
|
||||
* @returns {Transaction} calling instance for chaining
|
||||
*/
|
||||
Transaction.prototype.maxFee = function(fee) {
|
||||
if (typeof fee === 'number' && fee >= 0) {
|
||||
this._setMaxFee = true;
|
||||
this._maxFee = fee;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction._pathRewrite = function(path) {
|
||||
if (!Array.isArray(path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var newPath = path.map(function(node) {
|
||||
var newNode = { };
|
||||
|
||||
if (node.hasOwnProperty('account')) {
|
||||
newNode.account = UInt160.json_rewrite(node.account);
|
||||
}
|
||||
|
||||
if (node.hasOwnProperty('issuer')) {
|
||||
newNode.issuer = UInt160.json_rewrite(node.issuer);
|
||||
}
|
||||
|
||||
if (node.hasOwnProperty('currency')) {
|
||||
newNode.currency = Currency.json_rewrite(node.currency);
|
||||
}
|
||||
|
||||
if (node.hasOwnProperty('type_hex')) {
|
||||
newNode.type_hex = node.type_hex;
|
||||
}
|
||||
|
||||
return newNode;
|
||||
});
|
||||
|
||||
return newPath;
|
||||
};
|
||||
|
||||
Transaction.prototype.pathAdd = function(path) {
|
||||
if (Array.isArray(path)) {
|
||||
this.tx_json.Paths = this.tx_json.Paths || [];
|
||||
this.tx_json.Paths.push(Transaction._pathRewrite(path));
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
// --> paths: undefined or array of path
|
||||
// // A path is an array of objects containing some combination of: account, currency, issuer
|
||||
|
||||
Transaction.prototype.paths = function(paths) {
|
||||
if (Array.isArray(paths)) {
|
||||
for (var i=0, l=paths.length; i<l; i++) {
|
||||
this.pathAdd(paths[i]);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
// If the secret is in the config object, it does not need to be provided.
|
||||
Transaction.prototype.secret = function(secret) {
|
||||
this._secret = secret;
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.sendMax = function(send_max) {
|
||||
if (send_max) {
|
||||
this.tx_json.SendMax = Amount.json_rewrite(send_max);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
// tag should be undefined or a 32 bit integer.
|
||||
// YYY Add range checking for tag.
|
||||
Transaction.prototype.sourceTag = function(tag) {
|
||||
if (tag) {
|
||||
this.tx_json.SourceTag = tag;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
// --> rate: In billionths.
|
||||
Transaction.prototype.transferRate = function(rate) {
|
||||
this.tx_json.TransferRate = Number(rate);
|
||||
|
||||
if (this.tx_json.TransferRate < 1e9) {
|
||||
throw new Error('invalidTransferRate');
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Add flags to a transaction.
|
||||
// --> flags: undefined, _flag_, or [ _flags_ ]
|
||||
Transaction.prototype.setFlags = function(flags) {
|
||||
if (flags === void(0)) {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (typeof flags === 'number') {
|
||||
this.tx_json.Flags = flags;
|
||||
return this;
|
||||
}
|
||||
|
||||
var flag_set = Array.isArray(flags) ? flags : Array.prototype.slice.call(arguments);
|
||||
var transaction_flags = Transaction.flags[this.tx_json.TransactionType] || { };
|
||||
|
||||
for (var i=0, l=flag_set.length; i<l; i++) {
|
||||
var flag = flag_set[i];
|
||||
|
||||
if (transaction_flags.hasOwnProperty(flag)) {
|
||||
this.tx_json.Flags += transaction_flags[flag];
|
||||
} else {
|
||||
return this.emit('error', new RippleError('tejInvalidFlag'));
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a Memo to transaction. Memos can be used as key-value,
|
||||
* using the MemoType as a key
|
||||
*
|
||||
* @param {String} type
|
||||
* @param {String} data
|
||||
*/
|
||||
|
||||
Transaction.prototype.addMemo = function(type, data) {
|
||||
if (!/(undefined|string)/.test(typeof type)) {
|
||||
throw new Error('MemoType must be a string');
|
||||
}
|
||||
|
||||
if (!/(undefined|string)/.test(typeof data)) {
|
||||
throw new Error('MemoData must be a string');
|
||||
}
|
||||
|
||||
function toHex(str) {
|
||||
return sjcl.codec.hex.fromBits(sjcl.codec.utf8String.toBits(str));
|
||||
};
|
||||
|
||||
var memo = { };
|
||||
|
||||
if (type) {
|
||||
if (Transaction.MEMO_TYPES[type]) {
|
||||
//XXX Maybe in the future we want a schema validator for
|
||||
//memo types
|
||||
memo.MemoType = Transaction.MEMO_TYPES[type];
|
||||
} else {
|
||||
memo.MemoType = toHex(type);
|
||||
}
|
||||
}
|
||||
|
||||
if (data) {
|
||||
memo.MemoData = toHex(data);
|
||||
}
|
||||
|
||||
this.tx_json.Memos = (this.tx_json.Memos || []).concat({ Memo: memo });
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Options:
|
||||
// .domain() NYI
|
||||
// .flags()
|
||||
// .message_key() NYI
|
||||
// .transfer_rate()
|
||||
// .wallet_locator() NYI
|
||||
// .wallet_size() NYI
|
||||
|
||||
/**
|
||||
* Construct an 'AccountSet' transaction.
|
||||
*
|
||||
* Note that bit flags can be set using the .setFlags() method
|
||||
* but for 'AccountSet' transactions there is an additional way to
|
||||
* modify AccountRoot flags. The values available for the SetFlag
|
||||
* and ClearFlag are as follows:
|
||||
*
|
||||
* "asfRequireDest"
|
||||
* Require a destination tag
|
||||
* "asfRequireAuth"
|
||||
* Authorization is required to extend trust
|
||||
* "asfDisallowXRP"
|
||||
* XRP should not be sent to this account
|
||||
* "asfDisableMaster"
|
||||
* Disallow use of the master key
|
||||
*/
|
||||
|
||||
Transaction.prototype.accountSet = function(src, set_flag, clear_flag) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
src = options.source || options.from || options.account;
|
||||
set_flag = options.set_flag || options.set;
|
||||
clear_flag = options.clear_flag || options.clear;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Source address invalid');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'AccountSet';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
|
||||
var SetClearFlags = Transaction.set_clear_flags.AccountSet;
|
||||
|
||||
function prepareFlag(flag) {
|
||||
return (typeof flag === 'number') ? flag : (SetClearFlags[flag] || SetClearFlags['asf' + flag]);
|
||||
};
|
||||
|
||||
if (set_flag && (set_flag = prepareFlag(set_flag))) {
|
||||
this.tx_json.SetFlag = set_flag;
|
||||
}
|
||||
|
||||
if (clear_flag && (clear_flag = prepareFlag(clear_flag))) {
|
||||
this.tx_json.ClearFlag = clear_flag;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.claim = function(src, generator, public_key, signature) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
signature = options.signature;
|
||||
public_key = options.public_key;
|
||||
generator = options.generator;
|
||||
src = options.source || options.from || options.account;
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'Claim';
|
||||
this.tx_json.Generator = generator;
|
||||
this.tx_json.PublicKey = public_key;
|
||||
this.tx_json.Signature = signature;
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.offerCancel = function(src, sequence) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
sequence = options.sequence;
|
||||
src = options.source || options.from || options.account;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Source address invalid');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'OfferCancel';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
this.tx_json.OfferSequence = Number(sequence);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Options:
|
||||
// .set_flags()
|
||||
// --> expiration : if not undefined, Date or Number
|
||||
// --> cancel_sequence : if not undefined, Sequence
|
||||
Transaction.prototype.offerCreate = function(src, taker_pays, taker_gets, expiration, cancel_sequence) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
cancel_sequence = options.cancel_sequence;
|
||||
expiration = options.expiration;
|
||||
taker_gets = options.taker_gets || options.sell;
|
||||
taker_pays = options.taker_pays || options.buy;
|
||||
src = options.source || options.from || options.account;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Source address invalid');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'OfferCreate';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
this.tx_json.TakerPays = Amount.json_rewrite(taker_pays);
|
||||
this.tx_json.TakerGets = Amount.json_rewrite(taker_gets);
|
||||
|
||||
if (expiration) {
|
||||
this.tx_json.Expiration = utils.time.toRipple(expiration);
|
||||
}
|
||||
|
||||
if (cancel_sequence) {
|
||||
this.tx_json.OfferSequence = Number(cancel_sequence);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Construct a 'SetRegularKey' transaction.
|
||||
* If the RegularKey is set, the private key that corresponds to
|
||||
* it can be used to sign transactions instead of the master key
|
||||
*
|
||||
* The RegularKey must be a valid Ripple Address, or a Hash160 of
|
||||
* the public key corresponding to the new private signing key.
|
||||
*/
|
||||
|
||||
Transaction.prototype.setRegularKey = function(src, regular_key) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
src = options.address || options.account || options.from;
|
||||
regular_key = options.regular_key;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Source address invalid');
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(regular_key)) {
|
||||
throw new Error('RegularKey must be a valid Ripple Address (a Hash160 of the public key)');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'SetRegularKey';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
this.tx_json.RegularKey = UInt160.json_rewrite(regular_key);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Construct a 'payment' transaction.
|
||||
//
|
||||
// When a transaction is submitted:
|
||||
// - If the connection is reliable and the server is not merely forwarding and is not malicious,
|
||||
// --> src : UInt160 or String
|
||||
// --> dst : UInt160 or String
|
||||
// --> deliver_amount : Amount or String.
|
||||
//
|
||||
// Options:
|
||||
// .paths()
|
||||
// .build_path()
|
||||
// .destination_tag()
|
||||
// .path_add()
|
||||
// .secret()
|
||||
// .send_max()
|
||||
// .set_flags()
|
||||
// .source_tag()
|
||||
Transaction.prototype.payment = function(src, dst, amount) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
amount = options.amount;
|
||||
dst = options.destination || options.to;
|
||||
src = options.source || options.from || options.account;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Payment source address invalid');
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(dst)) {
|
||||
throw new Error('Payment destination address invalid');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'Payment';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
this.tx_json.Amount = Amount.json_rewrite(amount);
|
||||
this.tx_json.Destination = UInt160.json_rewrite(dst);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.trustSet =
|
||||
Transaction.prototype.rippleLineSet = function(src, limit, quality_in, quality_out) {
|
||||
if (typeof src === 'object') {
|
||||
var options = src;
|
||||
quality_out = options.quality_out;
|
||||
quality_in = options.quality_in;
|
||||
limit = options.limit;
|
||||
src = options.source || options.from || options.account;
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(src)) {
|
||||
throw new Error('Source address invalid');
|
||||
}
|
||||
|
||||
this.tx_json.TransactionType = 'TrustSet';
|
||||
this.tx_json.Account = UInt160.json_rewrite(src);
|
||||
|
||||
if (limit !== void(0)) {
|
||||
this.tx_json.LimitAmount = Amount.json_rewrite(limit);
|
||||
}
|
||||
|
||||
if (quality_in) {
|
||||
this.tx_json.QualityIn = quality_in;
|
||||
}
|
||||
|
||||
if (quality_out) {
|
||||
this.tx_json.QualityOut = quality_out;
|
||||
}
|
||||
|
||||
// XXX Throw an error if nothing is set.
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Submit a transaction to the network.
|
||||
Transaction.prototype.submit = function(callback) {
|
||||
var self = this;
|
||||
|
||||
this.callback = (typeof callback === 'function') ? callback : function(){};
|
||||
|
||||
function transactionError(error, message) {
|
||||
if (!(error instanceof RippleError)) {
|
||||
error = new RippleError(error, message);
|
||||
}
|
||||
self.callback(error);
|
||||
};
|
||||
|
||||
this._errorHandler = transactionError;
|
||||
|
||||
function transactionSuccess(message) {
|
||||
self.callback(null, message);
|
||||
};
|
||||
|
||||
this._successHandler = transactionSuccess;
|
||||
|
||||
this.on('error', function(){});
|
||||
|
||||
var account = this.tx_json.Account;
|
||||
|
||||
if (!this.remote) {
|
||||
return this.emit('error', new Error('No remote found'));
|
||||
}
|
||||
|
||||
if (!UInt160.is_valid(account)) {
|
||||
return this.emit('error', new RippleError('tejInvalidAccount', 'Account is missing or invalid'));
|
||||
}
|
||||
|
||||
// YYY Might check paths for invalid accounts.
|
||||
this.remote.account(account).submit(this);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Transaction.prototype.abort = function(callback) {
|
||||
var callback = (typeof callback === 'function') ? callback : function(){};
|
||||
if (!this.finalized) {
|
||||
this.once('final', callback);
|
||||
this.emit('abort');
|
||||
}
|
||||
};
|
||||
|
||||
Transaction.prototype.summary = function() {
|
||||
return Transaction.summary.call(this);
|
||||
};
|
||||
|
||||
Transaction.summary = function() {
|
||||
var result = {
|
||||
tx_json: this.tx_json,
|
||||
clientID: this._clientID,
|
||||
submittedIDs: this.submittedIDs,
|
||||
submissionAttempts: this.attempts,
|
||||
submitIndex: this.submitIndex,
|
||||
initialSubmitIndex: this.initialSubmitIndex,
|
||||
lastLedgerSequence: this.lastLedgerSequence,
|
||||
state: this.state,
|
||||
server: this._server ? this._server._opts.url : void(0),
|
||||
finalized: this.finalized
|
||||
};
|
||||
|
||||
if (this.result) {
|
||||
result.result = {
|
||||
engine_result : this.result.engine_result,
|
||||
engine_result_message: this.result.engine_result_message,
|
||||
ledger_hash : this.result.ledger_hash,
|
||||
ledger_index : this.result.ledger_index,
|
||||
transaction_hash : this.result.tx_json.hash
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.Transaction = Transaction;
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
@@ -1,679 +0,0 @@
|
||||
var util = require('util');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var Transaction = require('./transaction').Transaction;
|
||||
var RippleError = require('./rippleerror').RippleError;
|
||||
var PendingQueue = require('./transactionqueue').TransactionQueue;
|
||||
var log = require('./log').internal.sub('transactionmanager');
|
||||
|
||||
/**
|
||||
* @constructor TransactionManager
|
||||
* @param {Account} account
|
||||
*/
|
||||
|
||||
function TransactionManager(account) {
|
||||
EventEmitter.call(this);
|
||||
|
||||
var self = this;
|
||||
|
||||
this._account = account;
|
||||
this._accountID = account._account_id;
|
||||
this._remote = account._remote;
|
||||
this._nextSequence = void(0);
|
||||
this._maxFee = this._remote.max_fee;
|
||||
this._maxAttempts = this._remote.max_attempts;
|
||||
this._submissionTimeout = this._remote._submission_timeout;
|
||||
this._pending = new PendingQueue();
|
||||
|
||||
// Query remote server for next account sequence number
|
||||
this._loadSequence();
|
||||
|
||||
function transactionReceived(res) {
|
||||
var transaction = TransactionManager.normalizeTransaction(res);
|
||||
var sequence = transaction.tx_json.Sequence;
|
||||
var hash = transaction.tx_json.hash;
|
||||
|
||||
if (!transaction.validated) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._pending.addReceivedSequence(sequence);
|
||||
|
||||
// ND: we need to check against all submissions IDs
|
||||
var submission = self._pending.getSubmission(hash);
|
||||
|
||||
if (self._remote.trace) {
|
||||
log.info('transaction received:', transaction.tx_json);
|
||||
}
|
||||
|
||||
if (submission instanceof Transaction) {
|
||||
// ND: A `success` handler will `finalize` this later
|
||||
submission.emit('success', transaction);
|
||||
} else {
|
||||
self._pending.addReceivedId(hash, transaction);
|
||||
}
|
||||
};
|
||||
|
||||
this._account.on('transaction-outbound', transactionReceived);
|
||||
|
||||
this._remote.on('load_changed', this._adjustFees.bind(this));
|
||||
|
||||
function updatePendingStatus(ledger) {
|
||||
self._pending.forEach(function(pending) {
|
||||
switch (ledger.ledger_index - pending.submitIndex) {
|
||||
case 8:
|
||||
pending.emit('lost', ledger);
|
||||
break;
|
||||
case 4:
|
||||
pending.emit('missing', ledger);
|
||||
break;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
this._remote.on('ledger_closed', updatePendingStatus);
|
||||
|
||||
function remoteReconnected(callback) {
|
||||
var callback = (typeof callback === 'function') ? callback : function(){};
|
||||
|
||||
if (!self._pending.length) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
//Load account transaction history
|
||||
var options = {
|
||||
account: self._accountID,
|
||||
ledger_index_min: -1,
|
||||
ledger_index_max: -1,
|
||||
binary: true,
|
||||
parseBinary: true,
|
||||
limit: 100,
|
||||
filter: 'outbound'
|
||||
};
|
||||
|
||||
function accountTx(err, transactions) {
|
||||
if (!err && Array.isArray(transactions.transactions)) {
|
||||
transactions.transactions.forEach(transactionReceived);
|
||||
}
|
||||
|
||||
self._remote.on('ledger_closed', updatePendingStatus);
|
||||
|
||||
//Load next transaction sequence
|
||||
self._loadSequence(self._resubmit.bind(self));
|
||||
|
||||
callback();
|
||||
};
|
||||
|
||||
self._remote.requestAccountTx(options, accountTx);
|
||||
|
||||
self.emit('reconnect');
|
||||
};
|
||||
|
||||
function remoteDisconnected() {
|
||||
self._remote.once('connect', remoteReconnected);
|
||||
self._remote.removeListener('ledger_closed', updatePendingStatus);
|
||||
};
|
||||
|
||||
this._remote.on('disconnect', remoteDisconnected);
|
||||
|
||||
function saveTransaction(transaction) {
|
||||
self._remote.storage.saveTransaction(transaction.summary());
|
||||
};
|
||||
|
||||
if (this._remote.storage) {
|
||||
this.on('save', saveTransaction);
|
||||
}
|
||||
};
|
||||
|
||||
util.inherits(TransactionManager, EventEmitter);
|
||||
|
||||
//Normalize transactions received from account
|
||||
//transaction stream and account_tx
|
||||
TransactionManager.normalizeTransaction = function(tx) {
|
||||
var transaction = { };
|
||||
|
||||
Object.keys(tx).forEach(function(key) {
|
||||
transaction[key] = tx[key];
|
||||
});
|
||||
|
||||
if (!tx.engine_result) {
|
||||
// account_tx
|
||||
transaction = {
|
||||
engine_result: tx.meta.TransactionResult,
|
||||
tx_json: tx.tx,
|
||||
hash: tx.tx.hash,
|
||||
ledger_index: tx.tx.ledger_index,
|
||||
meta: tx.meta,
|
||||
type: 'transaction',
|
||||
validated: true
|
||||
};
|
||||
|
||||
transaction.result = transaction.engine_result;
|
||||
transaction.result_message = transaction.engine_result_message;
|
||||
}
|
||||
|
||||
if (!transaction.metadata) {
|
||||
transaction.metadata = transaction.meta;
|
||||
}
|
||||
|
||||
if (!transaction.tx_json) {
|
||||
transaction.tx_json = transaction.transaction;
|
||||
}
|
||||
|
||||
delete transaction.transaction;
|
||||
delete transaction.mmeta;
|
||||
delete transaction.meta;
|
||||
|
||||
return transaction;
|
||||
};
|
||||
|
||||
// Transaction fees are adjusted in real-time
|
||||
TransactionManager.prototype._adjustFees = function(loadData) {
|
||||
// ND: note, that `Fee` is a component of a transactionID
|
||||
var self = this;
|
||||
|
||||
if (!this._remote.local_fee) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._pending.forEach(function(pending) {
|
||||
var oldFee = pending.tx_json.Fee;
|
||||
var newFee = pending._computeFee();
|
||||
|
||||
function maxFeeExceeded() {
|
||||
pending.once('presubmit', function() {
|
||||
pending.emit('error', 'tejMaxFeeExceeded');
|
||||
});
|
||||
};
|
||||
|
||||
if (Number(newFee) > self._maxFee) {
|
||||
return maxFeeExceeded();
|
||||
}
|
||||
|
||||
pending.tx_json.Fee = newFee;
|
||||
pending.emit('fee_adjusted', oldFee, newFee);
|
||||
|
||||
if (self._remote.trace) {
|
||||
log.info('fee adjusted:', pending.tx_json, oldFee, newFee);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
//Fill an account transaction sequence
|
||||
TransactionManager.prototype._fillSequence = function(tx, callback) {
|
||||
var self = this;
|
||||
|
||||
function submitFill(sequence, callback) {
|
||||
var fill = self._remote.transaction();
|
||||
fill.account_set(self._accountID);
|
||||
fill.tx_json.Sequence = sequence;
|
||||
fill.once('submitted', callback);
|
||||
|
||||
// Secrets may be set on a per-transaction basis
|
||||
if (tx._secret) {
|
||||
fill.secret(tx._secret);
|
||||
}
|
||||
|
||||
fill.submit();
|
||||
};
|
||||
|
||||
function sequenceLoaded(err, sequence) {
|
||||
if (typeof sequence !== 'number') {
|
||||
return callback(new Error('Failed to fetch account transaction sequence'));
|
||||
}
|
||||
|
||||
var sequenceDif = tx.tx_json.Sequence - sequence;
|
||||
var submitted = 0;
|
||||
|
||||
;(function nextFill(sequence) {
|
||||
if (sequence >= tx.tx_json.Sequence) {
|
||||
return;
|
||||
}
|
||||
|
||||
submitFill(sequence, function() {
|
||||
if (++submitted === sequenceDif) {
|
||||
callback();
|
||||
} else {
|
||||
nextFill(sequence + 1);
|
||||
}
|
||||
});
|
||||
})(sequence);
|
||||
};
|
||||
|
||||
this._loadSequence(sequenceLoaded);
|
||||
};
|
||||
|
||||
TransactionManager.prototype._loadSequence = function(callback) {
|
||||
var self = this;
|
||||
|
||||
function sequenceLoaded(err, sequence) {
|
||||
if (typeof sequence === 'number') {
|
||||
self._nextSequence = sequence;
|
||||
self.emit('sequence_loaded', sequence);
|
||||
if (typeof callback === 'function') {
|
||||
callback(err, sequence);
|
||||
}
|
||||
} else {
|
||||
setTimeout(function() {
|
||||
self._loadSequence(callback);
|
||||
}, 1000 * 3);
|
||||
}
|
||||
};
|
||||
|
||||
this._account.getNextSequence(sequenceLoaded);
|
||||
};
|
||||
|
||||
TransactionManager.prototype._resubmit = function(ledgers, pending) {
|
||||
var self = this;
|
||||
var pending = pending ? [ pending ] : this._pending;
|
||||
var ledgers = Number(ledgers) || 0;
|
||||
|
||||
function resubmitTransaction(pending) {
|
||||
if (!pending || pending.finalized) {
|
||||
// Transaction has been finalized, nothing to do
|
||||
return;
|
||||
}
|
||||
|
||||
var hashCached = pending.findId(self._pending._idCache);
|
||||
|
||||
if (self._remote.trace) {
|
||||
log.info('resubmit:', pending.tx_json);
|
||||
}
|
||||
|
||||
if (hashCached) {
|
||||
return pending.emit('success', hashCached);
|
||||
}
|
||||
|
||||
while (self._pending.hasSequence(pending.tx_json.Sequence)) {
|
||||
//Sequence number has been consumed by another transaction
|
||||
pending.tx_json.Sequence += 1;
|
||||
|
||||
if (self._remote.trace) {
|
||||
log.info('incrementing sequence:', pending.tx_json);
|
||||
}
|
||||
}
|
||||
|
||||
self._request(pending);
|
||||
};
|
||||
|
||||
function resubmitTransactions() {
|
||||
;(function nextTransaction(i) {
|
||||
var transaction = pending[i];
|
||||
|
||||
if (!(transaction instanceof Transaction)) {
|
||||
return;
|
||||
}
|
||||
|
||||
transaction.once('submitted', function(m) {
|
||||
transaction.emit('resubmitted', m);
|
||||
|
||||
self._loadSequence();
|
||||
|
||||
if (++i < pending.length) {
|
||||
nextTransaction(i);
|
||||
}
|
||||
});
|
||||
|
||||
resubmitTransaction(transaction);
|
||||
})(0);
|
||||
};
|
||||
|
||||
this._waitLedgers(ledgers, resubmitTransactions);
|
||||
};
|
||||
|
||||
TransactionManager.prototype._waitLedgers = function(ledgers, callback) {
|
||||
if (ledgers < 1) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
var self = this;
|
||||
var closes = 0;
|
||||
|
||||
function ledgerClosed() {
|
||||
if (++closes < ledgers) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._remote.removeListener('ledger_closed', ledgerClosed);
|
||||
|
||||
callback();
|
||||
};
|
||||
|
||||
this._remote.on('ledger_closed', ledgerClosed);
|
||||
};
|
||||
|
||||
TransactionManager.prototype._request = function(tx) {
|
||||
var self = this;
|
||||
var remote = this._remote;
|
||||
|
||||
if (tx.attempts > this._maxAttempts) {
|
||||
return tx.emit('error', new RippleError('tejAttemptsExceeded'));
|
||||
}
|
||||
|
||||
if (tx.attempts > 0 && !remote.local_signing) {
|
||||
var message = ''
|
||||
+ 'It is not possible to resubmit transactions automatically safely without '
|
||||
+ 'synthesizing the transactionID locally. See `local_signing` config option';
|
||||
|
||||
return tx.emit('error', new RippleError('tejLocalSigningRequired', message));
|
||||
}
|
||||
|
||||
tx.emit('presubmit');
|
||||
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (remote.trace) {
|
||||
log.info('submit transaction:', tx.tx_json);
|
||||
}
|
||||
|
||||
function transactionProposed(message) {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If server is honest, don't expect a final if rejected.
|
||||
message.rejected = tx.isRejected(message.engine_result_code);
|
||||
|
||||
tx.emit('proposed', message);
|
||||
};
|
||||
|
||||
function transactionFailed(message) {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.engine_result) {
|
||||
case 'tefPAST_SEQ':
|
||||
self._resubmit(1, tx);
|
||||
break;
|
||||
case 'tefALREADY':
|
||||
if (tx.responses === tx.submissions) {
|
||||
tx.emit('error', message);
|
||||
} else {
|
||||
submitRequest.once('success', submitted);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
tx.emit('error', message);
|
||||
}
|
||||
};
|
||||
|
||||
function transactionRetry(message) {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._fillSequence(tx, function() {
|
||||
self._resubmit(1, tx);
|
||||
});
|
||||
};
|
||||
|
||||
function transactionFeeClaimed(message) {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
tx.emit('error', message);
|
||||
};
|
||||
|
||||
function transactionFailedLocal(message) {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self._remote.local_fee && (message.engine_result === 'telINSUF_FEE_P')) {
|
||||
self._resubmit(2, tx);
|
||||
} else {
|
||||
submissionError(message);
|
||||
}
|
||||
};
|
||||
|
||||
function submissionError(error) {
|
||||
// Finalized (e.g. aborted) transactions must stop all activity
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (TransactionManager._isTooBusy(error)) {
|
||||
self._resubmit(1, tx);
|
||||
} else {
|
||||
self._nextSequence--;
|
||||
tx.emit('error', error);
|
||||
}
|
||||
};
|
||||
|
||||
function submitted(message) {
|
||||
// Finalized (e.g. aborted) transactions must stop all activity
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ND: If for some unknown reason our hash wasn't computed correctly this is
|
||||
// an extra measure.
|
||||
if (message.tx_json && message.tx_json.hash) {
|
||||
tx.addId(message.tx_json.hash);
|
||||
}
|
||||
|
||||
message.result = message.engine_result || '';
|
||||
|
||||
tx.result = message;
|
||||
tx.responses += 1;
|
||||
|
||||
if (remote.trace) {
|
||||
log.info('submit response:', message);
|
||||
}
|
||||
|
||||
tx.emit('submitted', message);
|
||||
|
||||
switch (message.result.slice(0, 3)) {
|
||||
case 'tes':
|
||||
transactionProposed(message);
|
||||
break;
|
||||
case 'tec':
|
||||
transactionFeeClaimed(message);
|
||||
break;
|
||||
case 'ter':
|
||||
transactionRetry(message);
|
||||
break;
|
||||
case 'tef':
|
||||
transactionFailed(message);
|
||||
break;
|
||||
case 'tel':
|
||||
transactionFailedLocal(message);
|
||||
break;
|
||||
default:
|
||||
// tem
|
||||
submissionError(message);
|
||||
}
|
||||
};
|
||||
|
||||
var submitRequest = remote.requestSubmit();
|
||||
|
||||
submitRequest.once('error', submitted);
|
||||
submitRequest.once('success', submitted);
|
||||
|
||||
function prepareSubmit() {
|
||||
if (remote.local_signing) {
|
||||
// TODO: We are serializing twice, when we could/should be feeding the
|
||||
// tx_blob to `tx.hash()` which rebuilds it to sign it.
|
||||
submitRequest.tx_blob(tx.serialize().to_hex());
|
||||
|
||||
// ND: ecdsa produces a random `TxnSignature` field value, a component of
|
||||
// the hash. Attempting to identify a transaction via a hash synthesized
|
||||
// locally while using remote signing is inherently flawed.
|
||||
tx.addId(tx.hash());
|
||||
} else {
|
||||
// ND: `build_path` is completely ignored when doing local signing as
|
||||
// `Paths` is a component of the signed blob, the `tx_blob` is signed,
|
||||
// sealed and delivered, and the txn unmodified.
|
||||
// TODO: perhaps an exception should be raised if build_path is attempted
|
||||
// while local signing
|
||||
submitRequest.build_path(tx._build_path);
|
||||
submitRequest.secret(tx._secret);
|
||||
submitRequest.tx_json(tx.tx_json);
|
||||
}
|
||||
|
||||
if (tx._server) {
|
||||
submitRequest.server = tx._server;
|
||||
}
|
||||
|
||||
submitTransaction();
|
||||
};
|
||||
|
||||
function requestTimeout() {
|
||||
// ND: What if the response is just slow and we get a response that
|
||||
// `submitted` above will cause to have concurrent resubmit logic streams?
|
||||
// It's simpler to just mute handlers and look out for finalized
|
||||
// `transaction` messages.
|
||||
|
||||
// ND: We should audit the code for other potential multiple resubmit
|
||||
// streams. Connection/reconnection could be one? That's why it's imperative
|
||||
// that ALL transactionIDs sent over network are tracked.
|
||||
|
||||
// Finalized (e.g. aborted) transactions must stop all activity
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
tx.emit('timeout');
|
||||
|
||||
if (remote._connected) {
|
||||
if (remote.trace) {
|
||||
log.info('timeout:', tx.tx_json);
|
||||
}
|
||||
self._resubmit(3, tx);
|
||||
}
|
||||
};
|
||||
|
||||
function submitTransaction() {
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
submitRequest.timeout(self._submissionTimeout, requestTimeout);
|
||||
tx.submissions = submitRequest.broadcast();
|
||||
|
||||
tx.attempts++;
|
||||
tx.emit('postsubmit');
|
||||
};
|
||||
|
||||
tx.submitIndex = this._remote._ledger_current_index;
|
||||
|
||||
if (tx.attempts === 0) {
|
||||
tx.initialSubmitIndex = tx.submitIndex;
|
||||
}
|
||||
|
||||
if (!tx._setLastLedger) {
|
||||
// Honor LastLedgerSequence set by user of API. If
|
||||
// left unset by API, bump LastLedgerSequence
|
||||
tx.tx_json.LastLedgerSequence = tx.submitIndex + 8;
|
||||
}
|
||||
|
||||
tx.lastLedgerSequence = tx.tx_json.LastLedgerSequence;
|
||||
|
||||
if (remote.local_signing) {
|
||||
tx.sign(prepareSubmit);
|
||||
} else {
|
||||
prepareSubmit();
|
||||
}
|
||||
|
||||
return submitRequest;
|
||||
};
|
||||
|
||||
TransactionManager._isNoOp = function(transaction) {
|
||||
return (typeof transaction === 'object')
|
||||
&& (typeof transaction.tx_json === 'object')
|
||||
&& (transaction.tx_json.TransactionType === 'AccountSet')
|
||||
&& (transaction.tx_json.Flags === 0);
|
||||
};
|
||||
|
||||
TransactionManager._isRemoteError = function(error) {
|
||||
return (typeof error === 'object')
|
||||
&& (error.error === 'remoteError')
|
||||
&& (typeof error.remote === 'object');
|
||||
};
|
||||
|
||||
TransactionManager._isNotFound = function(error) {
|
||||
return TransactionManager._isRemoteError(error)
|
||||
&& /^(txnNotFound|transactionNotFound)$/.test(error.remote.error);
|
||||
};
|
||||
|
||||
TransactionManager._isTooBusy = function(error) {
|
||||
return TransactionManager._isRemoteError(error)
|
||||
&& (error.remote.error === 'tooBusy');
|
||||
};
|
||||
|
||||
/**
|
||||
* Entry point for TransactionManager submission
|
||||
*
|
||||
* @param {Transaction} tx
|
||||
*/
|
||||
|
||||
TransactionManager.prototype.submit = function(tx) {
|
||||
var self = this;
|
||||
var remote = this._remote;
|
||||
|
||||
// If sequence number is not yet known, defer until it is.
|
||||
if (typeof this._nextSequence !== 'number') {
|
||||
this.once('sequence_loaded', this.submit.bind(this, tx));
|
||||
return;
|
||||
}
|
||||
|
||||
// Finalized (e.g. aborted) transactions must stop all activity
|
||||
if (tx.finalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
function cleanup(message) {
|
||||
// ND: We can just remove this `tx` by identity
|
||||
self._pending.remove(tx);
|
||||
tx.emit('final', message);
|
||||
if (remote.trace) {
|
||||
log.info('transaction finalized:', tx.tx_json, self._pending.getLength());
|
||||
}
|
||||
};
|
||||
|
||||
tx.once('cleanup', cleanup);
|
||||
|
||||
tx.on('save', function() {
|
||||
self.emit('save', tx);
|
||||
});
|
||||
|
||||
tx.once('error', function(message) {
|
||||
tx._errorHandler(message);
|
||||
});
|
||||
|
||||
tx.once('success', function(message) {
|
||||
tx._successHandler(message);
|
||||
});
|
||||
|
||||
tx.once('abort', function() {
|
||||
tx.emit('error', new RippleError('tejAbort', 'Transaction aborted'));
|
||||
});
|
||||
|
||||
if (typeof tx.tx_json.Sequence !== 'number') {
|
||||
tx.tx_json.Sequence = this._nextSequence++;
|
||||
}
|
||||
|
||||
// Attach secret, associate transaction with a server, attach fee.
|
||||
// If the transaction can't complete, decrement sequence so that
|
||||
// subsequent transactions
|
||||
if (!tx.complete()) {
|
||||
this._nextSequence--;
|
||||
return;
|
||||
}
|
||||
|
||||
tx.attempts = 0;
|
||||
tx.submissions = 0;
|
||||
tx.responses = 0;
|
||||
|
||||
// ND: this is the ONLY place we put the tx into the queue. The
|
||||
// TransactionQueue queue is merely a list, so any mutations to tx._hash
|
||||
// will cause subsequent look ups (eg. inside 'transaction-outbound'
|
||||
// validated transaction clearing) to fail.
|
||||
this._pending.push(tx);
|
||||
this._request(tx);
|
||||
};
|
||||
|
||||
exports.TransactionManager = TransactionManager;
|
||||
@@ -1,23 +0,0 @@
|
||||
var utils = require('./utils');
|
||||
var extend = require('extend');
|
||||
var UInt = require('./uint').UInt;
|
||||
|
||||
//
|
||||
// UInt128 support
|
||||
//
|
||||
|
||||
var UInt128 = extend(function () {
|
||||
// Internal form: NaN or BigInteger
|
||||
this._value = NaN;
|
||||
}, UInt);
|
||||
|
||||
UInt128.width = 16;
|
||||
UInt128.prototype = extend({}, UInt.prototype);
|
||||
UInt128.prototype.constructor = UInt128;
|
||||
|
||||
var HEX_ZERO = UInt128.HEX_ZERO = '00000000000000000000000000000000';
|
||||
var HEX_ONE = UInt128.HEX_ONE = '00000000000000000000000000000000';
|
||||
var STR_ZERO = UInt128.STR_ZERO = utils.hexToString(HEX_ZERO);
|
||||
var STR_ONE = UInt128.STR_ONE = utils.hexToString(HEX_ONE);
|
||||
|
||||
exports.UInt128 = UInt128;
|
||||
@@ -1,23 +0,0 @@
|
||||
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;
|
||||
}, 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);
|
||||
|
||||
exports.UInt256 = UInt256;
|
||||
@@ -1,158 +0,0 @@
|
||||
function filterErr(code, done) {
|
||||
return function(e) {
|
||||
done(e.code !== code ? e : void(0));
|
||||
};
|
||||
};
|
||||
|
||||
function throwErr(done) {
|
||||
return function(e) {
|
||||
if (e) {
|
||||
throw e;
|
||||
}
|
||||
done();
|
||||
};
|
||||
};
|
||||
|
||||
function trace(comment, func) {
|
||||
return function() {
|
||||
console.log('%s: %s', trace, arguments.toString);
|
||||
func(arguments);
|
||||
};
|
||||
};
|
||||
|
||||
function arraySet(count, value) {
|
||||
var a = new Array(count);
|
||||
|
||||
for (var i=0; i<count; i++) {
|
||||
a[i] = value;
|
||||
}
|
||||
|
||||
return a;
|
||||
};
|
||||
|
||||
function hexToString(h) {
|
||||
var a = [];
|
||||
var i = 0;
|
||||
|
||||
if (h.length % 2) {
|
||||
a.push(String.fromCharCode(parseInt(h.substring(0, 1), 16)));
|
||||
i = 1;
|
||||
}
|
||||
|
||||
for (; i<h.length; i+=2) {
|
||||
a.push(String.fromCharCode(parseInt(h.substring(i, i+2), 16)));
|
||||
}
|
||||
|
||||
return a.join('');
|
||||
};
|
||||
|
||||
function stringToHex(s) {
|
||||
var result = '';
|
||||
for (var i=0; i<s.length; i++) {
|
||||
var b = s.charCodeAt(i);
|
||||
result += b < 16 ? '0' + b.toString(16) : b.toString(16);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
function stringToArray(s) {
|
||||
var a = new Array(s.length);
|
||||
|
||||
for (var i=0; i<a.length; i+=1) {
|
||||
a[i] = s.charCodeAt(i);
|
||||
}
|
||||
|
||||
return a;
|
||||
};
|
||||
|
||||
function hexToArray(h) {
|
||||
return stringToArray(hexToString(h));
|
||||
};
|
||||
|
||||
function chunkString(str, n, leftAlign) {
|
||||
var ret = [];
|
||||
var i=0, len=str.length;
|
||||
|
||||
if (leftAlign) {
|
||||
i = str.length % n;
|
||||
if (i) {
|
||||
ret.push(str.slice(0, i));
|
||||
}
|
||||
}
|
||||
|
||||
for(; i<len; i+=n) {
|
||||
ret.push(str.slice(i, n + i));
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
function assert(assertion, msg) {
|
||||
if (!assertion) {
|
||||
throw new Error('Assertion failed' + (msg ? ': ' + msg : '.'));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return unique values in array.
|
||||
*/
|
||||
function arrayUnique(arr) {
|
||||
var u = {}, a = [];
|
||||
|
||||
for (var i=0, l=arr.length; i<l; i++){
|
||||
var k = arr[i];
|
||||
if (u[k]) {
|
||||
continue;
|
||||
}
|
||||
a.push(k);
|
||||
u[k] = true;
|
||||
}
|
||||
|
||||
return a;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert a ripple epoch to a JavaScript timestamp.
|
||||
*
|
||||
* JavaScript timestamps are unix epoch in milliseconds.
|
||||
*/
|
||||
function toTimestamp(rpepoch) {
|
||||
return (rpepoch + 0x386D4380) * 1000;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert a JavaScript timestamp or Date to a Ripple epoch.
|
||||
*
|
||||
* JavaScript timestamps are unix epoch in milliseconds.
|
||||
*/
|
||||
function fromTimestamp(rpepoch) {
|
||||
if (rpepoch instanceof Date) {
|
||||
rpepoch = rpepoch.getTime();
|
||||
}
|
||||
|
||||
return Math.round(rpepoch / 1000) - 0x386D4380;
|
||||
};
|
||||
|
||||
exports.time = {
|
||||
fromRipple: toTimestamp,
|
||||
toRipple: fromTimestamp
|
||||
};
|
||||
|
||||
exports.trace = trace;
|
||||
exports.arraySet = arraySet;
|
||||
exports.hexToString = hexToString;
|
||||
exports.hexToArray = hexToArray;
|
||||
exports.stringToArray = stringToArray;
|
||||
exports.stringToHex = stringToHex;
|
||||
exports.chunkString = chunkString;
|
||||
exports.assert = assert;
|
||||
exports.arrayUnique = arrayUnique;
|
||||
exports.toTimestamp = toTimestamp;
|
||||
exports.fromTimestamp = fromTimestamp;
|
||||
|
||||
// Going up three levels is needed to escape the src-cov folder used for the
|
||||
// test coverage stuff.
|
||||
exports.sjcl = require('../../../build/sjcl');
|
||||
exports.jsbn = require('../../../src/js/jsbn/jsbn');
|
||||
|
||||
// vim:sw=2:sts=2:ts=8:et
|
||||
@@ -1,593 +0,0 @@
|
||||
var async = require('async');
|
||||
var blobClient = require('./blob').BlobClient;
|
||||
var AuthInfo = require('./authinfo').AuthInfo;
|
||||
var crypt = require('./crypt').Crypt;
|
||||
var log = require('./log').sub('vault');
|
||||
function VaultClient(opts) {
|
||||
|
||||
var self = this;
|
||||
|
||||
if (!opts) {
|
||||
opts = { };
|
||||
}
|
||||
|
||||
if (typeof opts === 'string') {
|
||||
opts = { domain: opts };
|
||||
}
|
||||
|
||||
this.domain = opts.domain || 'ripple.com';
|
||||
this.infos = { };
|
||||
};
|
||||
|
||||
/**
|
||||
* getAuthInfo
|
||||
* gets auth info for a username. returns authinfo
|
||||
* even if user does not exists (with exist set to false)
|
||||
* @param {string} username
|
||||
* @param {function} callback
|
||||
*/
|
||||
VaultClient.prototype.getAuthInfo = function (username, callback) {
|
||||
|
||||
AuthInfo.get(this.domain, username, function(err, authInfo) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (authInfo.version !== 3) {
|
||||
return callback(new Error('This wallet is incompatible with this version of the vault-client.'));
|
||||
}
|
||||
|
||||
if (!authInfo.pakdf) {
|
||||
return callback(new Error('No settings for PAKDF in auth packet.'));
|
||||
}
|
||||
|
||||
if (typeof authInfo.blobvault !== 'string') {
|
||||
return callback(new Error('No blobvault specified in the authinfo.'));
|
||||
}
|
||||
|
||||
callback(null, authInfo);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* _deriveLoginKeys
|
||||
* method designed for asnyc waterfall
|
||||
*/
|
||||
|
||||
VaultClient.prototype._deriveLoginKeys = function (authInfo, password, callback) {
|
||||
var normalizedUsername = authInfo.username.toLowerCase().replace(/-/g, '');
|
||||
|
||||
//derive login keys
|
||||
crypt.derive(authInfo.pakdf, 'login', normalizedUsername, password, function(err, keys) {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
callback(null, authInfo, password, keys);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* _deriveUnlockKey
|
||||
* method designed for asnyc waterfall
|
||||
*/
|
||||
|
||||
VaultClient.prototype._deriveUnlockKey = function (authInfo, password, keys, callback) {
|
||||
var normalizedUsername = authInfo.username.toLowerCase().replace(/-/g, '');
|
||||
|
||||
//derive unlock key
|
||||
crypt.derive(authInfo.pakdf, 'unlock', normalizedUsername, password, function(err, unlock) {
|
||||
if (err) {
|
||||
log.error('derive:', err);
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (!keys) {
|
||||
keys = { };
|
||||
}
|
||||
|
||||
keys.unlock = unlock.unlock;
|
||||
callback(null, authInfo, keys);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a ripple name from a given account address, if it has one
|
||||
* @param {string} address - Account address to query
|
||||
* @param {string} url - Url of blob vault
|
||||
*/
|
||||
|
||||
VaultClient.prototype.getRippleName = function(address, url, callback) {
|
||||
//use the url from previously retrieved authInfo, if necessary
|
||||
if (!url) {
|
||||
callback(new Error('Blob vault URL is required'));
|
||||
} else {
|
||||
blobClient.getRippleName(url, address, callback);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check blobvault for existance of username
|
||||
*
|
||||
* @param {string} username
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.exists = function(username, callback) {
|
||||
AuthInfo.get(this.domain, username.toLowerCase(), function(err, authInfo) {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
callback(null, !!authInfo.exists);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Authenticate and retrieve a decrypted blob using a ripple name and password
|
||||
*
|
||||
* @param {string} username
|
||||
* @param {string} password
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.login = function(username, password, device_id, callback) {
|
||||
var self = this;
|
||||
|
||||
var steps = [
|
||||
getAuthInfo,
|
||||
self._deriveLoginKeys,
|
||||
getBlob
|
||||
];
|
||||
|
||||
async.waterfall(steps, callback);
|
||||
|
||||
function getAuthInfo(callback) {
|
||||
self.getAuthInfo(username, function(err, authInfo){
|
||||
|
||||
if (authInfo && !authInfo.exists) {
|
||||
return callback(new Error('User does not exist.'));
|
||||
}
|
||||
|
||||
return callback (err, authInfo, password);
|
||||
});
|
||||
}
|
||||
|
||||
function getBlob(authInfo, password, keys, callback) {
|
||||
var options = {
|
||||
url : authInfo.blobvault,
|
||||
blob_id : keys.id,
|
||||
key : keys.crypt,
|
||||
device_id : device_id
|
||||
};
|
||||
|
||||
blobClient.get(options, function(err, blob) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
//save for relogin
|
||||
self.infos[keys.id] = authInfo;
|
||||
|
||||
//migrate missing fields
|
||||
if (blob.missing_fields) {
|
||||
if (blob.missing_fields.encrypted_blobdecrypt_key) {
|
||||
log.info('migration: saving encrypted blob decrypt key');
|
||||
authInfo.blob = blob;
|
||||
//get the key to unlock the secret, then update the blob keys
|
||||
self._deriveUnlockKey(authInfo, password, keys, updateKeys);
|
||||
}
|
||||
}
|
||||
|
||||
callback(null, {
|
||||
blob : blob,
|
||||
username : authInfo.username,
|
||||
verified : authInfo.emailVerified
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
function updateKeys (err, params, keys) {
|
||||
if (err || !keys.unlock) {
|
||||
return; //unable to unlock
|
||||
}
|
||||
|
||||
var secret;
|
||||
try {
|
||||
secret = crypt.decrypt(keys.unlock, params.blob.encrypted_secret);
|
||||
} catch (error) {
|
||||
return log.error('decrypt:', error);
|
||||
}
|
||||
|
||||
options = {
|
||||
username : params.username,
|
||||
blob : params.blob,
|
||||
masterkey : secret,
|
||||
keys : keys
|
||||
};
|
||||
|
||||
blobClient.updateKeys(options, function(err, resp){
|
||||
if (err) {
|
||||
log.error('updateKeys:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Retreive and decrypt blob using a blob url, id and crypt derived previously.
|
||||
*
|
||||
* @param {string} url - Blob vault url
|
||||
* @param {string} id - Blob id from previously retreived blob
|
||||
* @param {string} key - Blob decryption key
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.relogin = function(url, id, key, device_id, callback) {
|
||||
//use the url from previously retrieved authInfo, if necessary
|
||||
if (!url && this.infos[id]) {
|
||||
url = this.infos[id].blobvault;
|
||||
}
|
||||
|
||||
if (!url) {
|
||||
return callback(new Error('Blob vault URL is required'));
|
||||
}
|
||||
|
||||
var options = {
|
||||
url : url,
|
||||
blob_id : id,
|
||||
key : key,
|
||||
device_id : device_id
|
||||
};
|
||||
|
||||
blobClient.get(options, function(err, blob) {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
callback (null, { blob: blob });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrypt the secret key using a username and password
|
||||
*
|
||||
* @param {string} username
|
||||
* @param {string} password
|
||||
* @param {string} encryptSecret
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.unlock = function(username, password, encryptSecret, fn) {
|
||||
var self = this;
|
||||
|
||||
var steps = [
|
||||
getAuthInfo,
|
||||
self._deriveUnlockKey,
|
||||
unlockSecret
|
||||
];
|
||||
|
||||
async.waterfall(steps, fn);
|
||||
|
||||
function getAuthInfo(callback) {
|
||||
self.getAuthInfo(username, function(err, authInfo){
|
||||
|
||||
if (authInfo && !authInfo.exists) {
|
||||
return callback(new Error('User does not exist.'));
|
||||
}
|
||||
|
||||
return callback (err, authInfo, password, {});
|
||||
});
|
||||
}
|
||||
|
||||
function unlockSecret (authinfo, keys, callback) {
|
||||
|
||||
var secret;
|
||||
try {
|
||||
secret = crypt.decrypt(keys.unlock, encryptSecret);
|
||||
} catch (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback(null, {
|
||||
keys : keys,
|
||||
secret : secret
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the decrypted blob and secret key in one step using
|
||||
* the username and password
|
||||
*
|
||||
* @param {string} username
|
||||
* @param {string} password
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.loginAndUnlock = function(username, password, device_id, fn) {
|
||||
var self = this;
|
||||
|
||||
var steps = [
|
||||
login,
|
||||
deriveUnlockKey,
|
||||
unlockSecret
|
||||
];
|
||||
|
||||
async.waterfall(steps, fn);
|
||||
|
||||
function login (callback) {
|
||||
self.login(username, password, device_id, function(err, resp) {
|
||||
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (!resp.blob || !resp.blob.encrypted_secret) {
|
||||
return callback(new Error('Unable to retrieve blob and secret.'));
|
||||
}
|
||||
|
||||
if (!resp.blob.id || !resp.blob.key) {
|
||||
return callback(new Error('Unable to retrieve keys.'));
|
||||
}
|
||||
|
||||
//get authInfo via id - would have been saved from login
|
||||
var authInfo = self.infos[resp.blob.id];
|
||||
|
||||
if (!authInfo) {
|
||||
return callback(new Error('Unable to find authInfo'));
|
||||
}
|
||||
|
||||
callback(null, authInfo, password, resp.blob);
|
||||
});
|
||||
};
|
||||
|
||||
function deriveUnlockKey (authInfo, password, blob, callback) {
|
||||
self._deriveUnlockKey(authInfo, password, null, function(err, authInfo, keys){
|
||||
callback(err, keys.unlock, authInfo, blob);
|
||||
});
|
||||
};
|
||||
|
||||
function unlockSecret (unlock, authInfo, blob, callback) {
|
||||
var secret;
|
||||
try {
|
||||
secret = crypt.decrypt(unlock, blob.encrypted_secret);
|
||||
} catch (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback(null, {
|
||||
blob : blob,
|
||||
unlock : unlock,
|
||||
secret : secret,
|
||||
username : authInfo.username,
|
||||
verified : authInfo.emailVerified
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Verify an email address for an existing user
|
||||
*
|
||||
* @param {string} username
|
||||
* @param {string} token - Verification token
|
||||
* @param {function} fn - Callback function
|
||||
*/
|
||||
|
||||
VaultClient.prototype.verify = function(username, token, callback) {
|
||||
var self = this;
|
||||
|
||||
self.getAuthInfo(username, function (err, authInfo){
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
blobClient.verify(authInfo.blobvault, username.toLowerCase(), token, callback);
|
||||
});
|
||||
};
|
||||
|
||||
/*
|
||||
* changePassword
|
||||
* @param {object} options
|
||||
* @param {string} options.username
|
||||
* @param {string} options.password
|
||||
* @param {string} options.masterkey
|
||||
* @param {object} options.blob
|
||||
*/
|
||||
|
||||
VaultClient.prototype.changePassword = function (options, fn) {
|
||||
var self = this;
|
||||
var password = String(options.password).trim();
|
||||
|
||||
var steps = [
|
||||
getAuthInfo,
|
||||
self._deriveLoginKeys,
|
||||
self._deriveUnlockKey,
|
||||
changePassword
|
||||
];
|
||||
|
||||
async.waterfall(steps, fn);
|
||||
|
||||
function getAuthInfo(callback) {
|
||||
self.getAuthInfo(options.username, function(err, authInfo) {
|
||||
return callback (err, authInfo, password);
|
||||
});
|
||||
};
|
||||
|
||||
function changePassword (authInfo, keys, callback) {
|
||||
options.keys = keys;
|
||||
blobClient.updateKeys(options, callback);
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* rename
|
||||
* rename a ripple account
|
||||
* @param {object} options
|
||||
* @param {string} options.username
|
||||
* @param {string} options.new_username
|
||||
* @param {string} options.password
|
||||
* @param {string} options.masterkey
|
||||
* @param {object} options.blob
|
||||
* @param {function} fn
|
||||
*/
|
||||
|
||||
VaultClient.prototype.rename = function (options, fn) {
|
||||
var self = this;
|
||||
var new_username = String(options.new_username).trim();
|
||||
var password = String(options.password).trim();
|
||||
|
||||
var steps = [
|
||||
getAuthInfo,
|
||||
self._deriveLoginKeys,
|
||||
self._deriveUnlockKey,
|
||||
renameBlob
|
||||
];
|
||||
|
||||
async.waterfall(steps, fn);
|
||||
|
||||
function getAuthInfo(callback) {
|
||||
self.getAuthInfo(new_username, function(err, authInfo){
|
||||
|
||||
if (authInfo && authInfo.exists) {
|
||||
return callback(new Error('username already taken.'));
|
||||
} else {
|
||||
authInfo.username = new_username;
|
||||
}
|
||||
|
||||
return callback (err, authInfo, password);
|
||||
});
|
||||
};
|
||||
|
||||
function renameBlob (authInfo, keys, callback) {
|
||||
options.keys = keys;
|
||||
blobClient.rename(options, callback);
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Register a new user and save to the blob vault
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {string} options.username
|
||||
* @param {string} options.password
|
||||
* @param {string} options.masterkey //optional, will create if absent
|
||||
* @param {string} options.email
|
||||
* @param {string} options.activateLink
|
||||
* @param {object} options.oldUserBlob //optional
|
||||
* @param {function} fn
|
||||
*/
|
||||
|
||||
VaultClient.prototype.register = function(options, fn) {
|
||||
var self = this;
|
||||
var username = String(options.username).trim();
|
||||
var password = String(options.password).trim();
|
||||
var result = self.validateUsername(username);
|
||||
|
||||
if (!result.valid) {
|
||||
return fn(new Error('invalid username.'));
|
||||
}
|
||||
|
||||
var steps = [
|
||||
getAuthInfo,
|
||||
self._deriveLoginKeys,
|
||||
self._deriveUnlockKey,
|
||||
create
|
||||
];
|
||||
|
||||
async.waterfall(steps, fn);
|
||||
|
||||
function getAuthInfo(callback) {
|
||||
self.getAuthInfo(username, function(err, authInfo){
|
||||
return callback (err, authInfo, password);
|
||||
});
|
||||
};
|
||||
|
||||
function create(authInfo, keys, callback) {
|
||||
var params = {
|
||||
url : authInfo.blobvault,
|
||||
id : keys.id,
|
||||
crypt : keys.crypt,
|
||||
unlock : keys.unlock,
|
||||
username : username,
|
||||
email : options.email,
|
||||
masterkey : options.masterkey || crypt.createMaster(),
|
||||
activateLink : options.activateLink,
|
||||
oldUserBlob : options.oldUserBlob,
|
||||
domain : options.domain
|
||||
};
|
||||
|
||||
blobClient.create(params, function(err, blob) {
|
||||
if (err) {
|
||||
callback(err);
|
||||
} else {
|
||||
callback(null, {
|
||||
blob : blob,
|
||||
username : username
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* validateUsername
|
||||
* check username for validity
|
||||
*/
|
||||
|
||||
VaultClient.prototype.validateUsername = function (username) {
|
||||
username = String(username).trim();
|
||||
var result = {
|
||||
valid : false,
|
||||
reason : ''
|
||||
};
|
||||
|
||||
if (username.length < 2) {
|
||||
result.reason = 'tooshort';
|
||||
} else if (username.length > 20) {
|
||||
result.reason = 'toolong';
|
||||
} else if (!/^[a-zA-Z0-9\-]+$/.exec(username)) {
|
||||
result.reason = 'charset';
|
||||
} else if (/^-/.exec(username)) {
|
||||
result.reason = 'starthyphen';
|
||||
} else if (/-$/.exec(username)) {
|
||||
result.reason = 'endhyphen';
|
||||
} else if (/--/.exec(username)) {
|
||||
result.reason = 'multhyphen';
|
||||
} else {
|
||||
result.valid = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* generateDeviceID
|
||||
* create a new random device ID for 2FA
|
||||
*/
|
||||
VaultClient.prototype.generateDeviceID = function () {
|
||||
return crypt.createSecret(4);
|
||||
};
|
||||
|
||||
/*** pass thru some blob client function ***/
|
||||
|
||||
VaultClient.prototype.resendEmail = blobClient.resendEmail;
|
||||
|
||||
VaultClient.prototype.recoverBlob = blobClient.recoverBlob;
|
||||
|
||||
VaultClient.prototype.deleteBlob = blobClient.deleteBlob;
|
||||
|
||||
VaultClient.prototype.requestToken = blobClient.requestToken;
|
||||
|
||||
VaultClient.prototype.verifyToken = blobClient.verifyToken;
|
||||
|
||||
VaultClient.prototype.getAttestation = blobClient.getAttestation;
|
||||
|
||||
VaultClient.prototype.updateAttestation = blobClient.updateAttestation;
|
||||
|
||||
VaultClient.prototype.getAttestationSummary = blobClient.getAttestationSummary;
|
||||
|
||||
//export by name
|
||||
exports.VaultClient = VaultClient;
|
||||
@@ -1,8 +0,0 @@
|
||||
var sjcl = require('./utils').sjcl;
|
||||
|
||||
var WalletGenerator = require('ripple-wallet-generator')({
|
||||
sjcl: sjcl
|
||||
});
|
||||
|
||||
module.exports = WalletGenerator;
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
sjcl.bn.prototype.jacobi = function (that) {
|
||||
var a = this;
|
||||
that = new sjcl.bn(that);
|
||||
|
||||
if (that.sign() === -1) return;
|
||||
|
||||
// 1. If a = 0 then return(0).
|
||||
if (a.equals(0)) { return 0; }
|
||||
|
||||
// 2. If a = 1 then return(1).
|
||||
if (a.equals(1)) { return 1; }
|
||||
|
||||
var s = 0;
|
||||
|
||||
// 3. Write a = 2^e * a1, where a1 is odd.
|
||||
var e = 0;
|
||||
while (!a.testBit(e)) e++;
|
||||
var a1 = a.shiftRight(e);
|
||||
|
||||
// 4. If e is even then set s ← 1.
|
||||
if ((e & 1) === 0) {
|
||||
s = 1;
|
||||
} else {
|
||||
var residue = that.modInt(8);
|
||||
|
||||
if (residue === 1 || residue === 7) {
|
||||
// Otherwise set s ← 1 if n ≡ 1 or 7 (mod 8)
|
||||
s = 1;
|
||||
} else if (residue === 3 || residue === 5) {
|
||||
// Or set s ← −1 if n ≡ 3 or 5 (mod 8).
|
||||
s = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. If n ≡ 3 (mod 4) and a1 ≡ 3 (mod 4) then set s ← −s.
|
||||
if (that.modInt(4) === 3 && a1.modInt(4) === 3) {
|
||||
s = -s;
|
||||
}
|
||||
|
||||
if (a1.equals(1)) {
|
||||
return s;
|
||||
} else {
|
||||
return s * that.mod(a1).jacobi(a1);
|
||||
}
|
||||
};
|
||||
@@ -1,156 +0,0 @@
|
||||
sjcl.bn.prototype.invDigit = function ()
|
||||
{
|
||||
var radixMod = 1 + this.radixMask;
|
||||
|
||||
if (this.limbs.length < 1) return 0;
|
||||
var x = this.limbs[0];
|
||||
if ((x&1) == 0) return 0;
|
||||
var y = x&3; // y == 1/x mod 2^2
|
||||
y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
|
||||
y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
|
||||
y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
|
||||
// last step - calculate inverse mod DV directly;
|
||||
// assumes 16 < radixMod <= 32 and assumes ability to handle 48-bit ints
|
||||
y = (y*(2-x*y%radixMod))%radixMod; // y == 1/x mod 2^dbits
|
||||
// we really want the negative inverse, and -DV < y < DV
|
||||
return (y>0)?radixMod-y:-y;
|
||||
};
|
||||
|
||||
// returns bit length of the integer x
|
||||
function nbits(x) {
|
||||
var r = 1, t;
|
||||
if((t=x>>>16) != 0) { x = t; r += 16; }
|
||||
if((t=x>>8) != 0) { x = t; r += 8; }
|
||||
if((t=x>>4) != 0) { x = t; r += 4; }
|
||||
if((t=x>>2) != 0) { x = t; r += 2; }
|
||||
if((t=x>>1) != 0) { x = t; r += 1; }
|
||||
return r;
|
||||
}
|
||||
|
||||
// JSBN-style add and multiply for SJCL w/ 24 bit radix
|
||||
sjcl.bn.prototype.am = function (i,x,w,j,c,n) {
|
||||
var xl = x&0xfff, xh = x>>12;
|
||||
while (--n >= 0) {
|
||||
var l = this.limbs[i]&0xfff;
|
||||
var h = this.limbs[i++]>>12;
|
||||
var m = xh*l+h*xl;
|
||||
l = xl*l+((m&0xfff)<<12)+w.limbs[j]+c;
|
||||
c = (l>>24)+(m>>12)+xh*h;
|
||||
w.limbs[j++] = l&0xffffff;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
var Montgomery = function (m)
|
||||
{
|
||||
this.m = m;
|
||||
this.mt = m.limbs.length;
|
||||
this.mt2 = this.mt * 2;
|
||||
this.mp = m.invDigit();
|
||||
this.mpl = this.mp&0x7fff;
|
||||
this.mph = this.mp>>15;
|
||||
this.um = (1<<(m.radix-15))-1;
|
||||
};
|
||||
|
||||
Montgomery.prototype.reduce = function (x)
|
||||
{
|
||||
var radixMod = x.radixMask + 1;
|
||||
while (x.limbs.length <= this.mt2) // pad x so am has enough room later
|
||||
x.limbs[x.limbs.length] = 0;
|
||||
for (var i = 0; i < this.mt; ++i) {
|
||||
// faster way of calculating u0 = x[i]*mp mod 2^radix
|
||||
var j = x.limbs[i]&0x7fff;
|
||||
var u0 = (j*this.mpl+(((j*this.mph+(x.limbs[i]>>15)*this.mpl)&this.um)<<15))&x.radixMask;
|
||||
// use am to combine the multiply-shift-add into one call
|
||||
j = i+this.mt;
|
||||
x.limbs[j] += this.m.am(0,u0,x,i,0,this.mt);
|
||||
// propagate carry
|
||||
while (x.limbs[j] >= radixMod) { x.limbs[j] -= radixMod; x.limbs[++j]++; }
|
||||
}
|
||||
x.trim();
|
||||
x = x.shiftRight(this.mt * this.m.radix);
|
||||
if (x.greaterEquals(this.m)) x = x.sub(this.m);
|
||||
return x.trim().normalize().reduce();
|
||||
};
|
||||
|
||||
Montgomery.prototype.square = function (x)
|
||||
{
|
||||
return this.reduce(x.square());
|
||||
};
|
||||
|
||||
Montgomery.prototype.multiply = function (x, y)
|
||||
{
|
||||
return this.reduce(x.mul(y));
|
||||
};
|
||||
|
||||
Montgomery.prototype.convert = function (x)
|
||||
{
|
||||
return x.abs().shiftLeft(this.mt * this.m.radix).mod(this.m);
|
||||
};
|
||||
|
||||
Montgomery.prototype.revert = function (x)
|
||||
{
|
||||
return this.reduce(x.copy());
|
||||
};
|
||||
|
||||
sjcl.bn.prototype.powermodMontgomery = function (e, m)
|
||||
{
|
||||
var i = e.bitLength(), k, r = new this._class(1);
|
||||
|
||||
if (i <= 0) return r;
|
||||
else if (i < 18) k = 1;
|
||||
else if (i < 48) k = 3;
|
||||
else if (i < 144) k = 4;
|
||||
else if (i < 768) k = 5;
|
||||
else k = 6;
|
||||
|
||||
if (i < 8 || !m.testBit(0)) {
|
||||
// For small exponents and even moduli, use a simple square-and-multiply
|
||||
// algorithm.
|
||||
return this.powermod(e, m);
|
||||
}
|
||||
|
||||
var z = new Montgomery(m);
|
||||
|
||||
e.trim().normalize();
|
||||
|
||||
// precomputation
|
||||
var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
|
||||
g[1] = z.convert(this);
|
||||
if (k > 1) {
|
||||
var g2 = z.square(g[1]);
|
||||
|
||||
while (n <= km) {
|
||||
g[n] = z.multiply(g2, g[n-2]);
|
||||
n += 2;
|
||||
}
|
||||
}
|
||||
|
||||
var j = e.limbs.length-1, w, is1 = true, r2 = new this._class(), t;
|
||||
i = nbits(e.limbs[j])-1;
|
||||
while (j >= 0) {
|
||||
if (i >= k1) w = (e.limbs[j]>>(i-k1))&km;
|
||||
else {
|
||||
w = (e.limbs[j]&((1<<(i+1))-1))<<(k1-i);
|
||||
if (j > 0) w |= e.limbs[j-1]>>(this.radix+i-k1);
|
||||
}
|
||||
|
||||
n = k;
|
||||
while ((w&1) == 0) { w >>= 1; --n; }
|
||||
if ((i -= n) < 0) { i += this.radix; --j; }
|
||||
if (is1) { // ret == 1, don't bother squaring or multiplying it
|
||||
r = g[w].copy();
|
||||
is1 = false;
|
||||
} else {
|
||||
while (n > 1) { r2 = z.square(r); r = z.square(r2); n -= 2; }
|
||||
if (n > 0) r2 = z.square(r); else { t = r; r = r2; r2 = t; }
|
||||
r = z.multiply(r2,g[w]);
|
||||
}
|
||||
|
||||
while (j >= 0 && (e.limbs[j]&(1<<i)) == 0) {
|
||||
r2 = z.square(r); t = r; r = r2; r2 = t;
|
||||
if (--i < 0) { i = this.radix-1; --j; }
|
||||
}
|
||||
}
|
||||
return z.revert(r);
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
/** @fileOverview Javascript RIPEMD-160 implementation.
|
||||
*
|
||||
* @author Artem S Vybornov <vybornov@gmail.com>
|
||||
*/
|
||||
(function() {
|
||||
|
||||
/**
|
||||
* Context for a RIPEMD-160 operation in progress.
|
||||
* @constructor
|
||||
* @class RIPEMD, 160 bits.
|
||||
*/
|
||||
sjcl.hash.ripemd160 = function (hash) {
|
||||
if (hash) {
|
||||
this._h = hash._h.slice(0);
|
||||
this._buffer = hash._buffer.slice(0);
|
||||
this._length = hash._length;
|
||||
} else {
|
||||
this.reset();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Hash a string or an array of words.
|
||||
* @static
|
||||
* @param {bitArray|String} data the data to hash.
|
||||
* @return {bitArray} The hash value, an array of 5 big-endian words.
|
||||
*/
|
||||
sjcl.hash.ripemd160.hash = function (data) {
|
||||
return (new sjcl.hash.ripemd160()).update(data).finalize();
|
||||
};
|
||||
|
||||
sjcl.hash.ripemd160.prototype = {
|
||||
/**
|
||||
* Reset the hash state.
|
||||
* @return this
|
||||
*/
|
||||
reset: function () {
|
||||
this._h = _h0.slice(0);
|
||||
this._buffer = [];
|
||||
this._length = 0;
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset the hash state.
|
||||
* @param {bitArray|String} data the data to hash.
|
||||
* @return this
|
||||
*/
|
||||
update: function (data) {
|
||||
if ( typeof data === "string" )
|
||||
data = sjcl.codec.utf8String.toBits(data);
|
||||
|
||||
var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),
|
||||
ol = this._length,
|
||||
nl = this._length = ol + sjcl.bitArray.bitLength(data);
|
||||
for (i = 512+ol & -512; i <= nl; i+= 512) {
|
||||
var words = b.splice(0,16);
|
||||
for ( var w = 0; w < 16; ++w )
|
||||
words[w] = _cvt(words[w]);
|
||||
|
||||
_block.call( this, words );
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Complete hashing and output the hash value.
|
||||
* @return {bitArray} The hash value, an array of 5 big-endian words.
|
||||
*/
|
||||
finalize: function () {
|
||||
var b = sjcl.bitArray.concat( this._buffer, [ sjcl.bitArray.partial(1,1) ] ),
|
||||
l = ( this._length + 1 ) % 512,
|
||||
z = ( l > 448 ? 512 : 448 ) - l % 448,
|
||||
zp = z % 32;
|
||||
|
||||
if ( zp > 0 )
|
||||
b = sjcl.bitArray.concat( b, [ sjcl.bitArray.partial(zp,0) ] )
|
||||
for ( ; z >= 32; z -= 32 )
|
||||
b.push(0);
|
||||
|
||||
b.push( _cvt( this._length | 0 ) );
|
||||
b.push( _cvt( Math.floor(this._length / 0x100000000) ) );
|
||||
|
||||
while ( b.length ) {
|
||||
var words = b.splice(0,16);
|
||||
for ( var w = 0; w < 16; ++w )
|
||||
words[w] = _cvt(words[w]);
|
||||
|
||||
_block.call( this, words );
|
||||
}
|
||||
|
||||
var h = this._h;
|
||||
this.reset();
|
||||
|
||||
for ( var w = 0; w < 5; ++w )
|
||||
h[w] = _cvt(h[w]);
|
||||
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
var _h0 = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
|
||||
|
||||
var _k1 = [ 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e ];
|
||||
var _k2 = [ 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000 ];
|
||||
for ( var i = 4; i >= 0; --i ) {
|
||||
for ( var j = 1; j < 16; ++j ) {
|
||||
_k1.splice(i,0,_k1[i]);
|
||||
_k2.splice(i,0,_k2[i]);
|
||||
}
|
||||
}
|
||||
|
||||
var _r1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
|
||||
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
|
||||
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
|
||||
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ];
|
||||
var _r2 = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
|
||||
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
|
||||
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
|
||||
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
|
||||
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ];
|
||||
|
||||
var _s1 = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
|
||||
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
|
||||
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
|
||||
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
|
||||
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
|
||||
var _s2 = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
|
||||
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
|
||||
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
|
||||
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
|
||||
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
|
||||
|
||||
function _f0(x,y,z) {
|
||||
return x ^ y ^ z;
|
||||
};
|
||||
|
||||
function _f1(x,y,z) {
|
||||
return (x & y) | (~x & z);
|
||||
};
|
||||
|
||||
function _f2(x,y,z) {
|
||||
return (x | ~y) ^ z;
|
||||
};
|
||||
|
||||
function _f3(x,y,z) {
|
||||
return (x & z) | (y & ~z);
|
||||
};
|
||||
|
||||
function _f4(x,y,z) {
|
||||
return x ^ (y | ~z);
|
||||
};
|
||||
|
||||
function _rol(n,l) {
|
||||
return (n << l) | (n >>> (32-l));
|
||||
}
|
||||
|
||||
function _cvt(n) {
|
||||
return ( (n & 0xff << 0) << 24 )
|
||||
| ( (n & 0xff << 8) << 8 )
|
||||
| ( (n & 0xff << 16) >>> 8 )
|
||||
| ( (n & 0xff << 24) >>> 24 );
|
||||
}
|
||||
|
||||
function _block(X) {
|
||||
var A1 = this._h[0], B1 = this._h[1], C1 = this._h[2], D1 = this._h[3], E1 = this._h[4],
|
||||
A2 = this._h[0], B2 = this._h[1], C2 = this._h[2], D2 = this._h[3], E2 = this._h[4];
|
||||
|
||||
var j = 0, T;
|
||||
|
||||
for ( ; j < 16; ++j ) {
|
||||
T = _rol( A1 + _f0(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;
|
||||
A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;
|
||||
T = _rol( A2 + _f4(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;
|
||||
A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }
|
||||
for ( ; j < 32; ++j ) {
|
||||
T = _rol( A1 + _f1(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;
|
||||
A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;
|
||||
T = _rol( A2 + _f3(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;
|
||||
A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }
|
||||
for ( ; j < 48; ++j ) {
|
||||
T = _rol( A1 + _f2(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;
|
||||
A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;
|
||||
T = _rol( A2 + _f2(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;
|
||||
A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }
|
||||
for ( ; j < 64; ++j ) {
|
||||
T = _rol( A1 + _f3(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;
|
||||
A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;
|
||||
T = _rol( A2 + _f1(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;
|
||||
A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }
|
||||
for ( ; j < 80; ++j ) {
|
||||
T = _rol( A1 + _f4(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;
|
||||
A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;
|
||||
T = _rol( A2 + _f0(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;
|
||||
A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }
|
||||
|
||||
T = this._h[1] + C1 + D2;
|
||||
this._h[1] = this._h[2] + D1 + E2;
|
||||
this._h[2] = this._h[3] + E1 + A2;
|
||||
this._h[3] = this._h[4] + A1 + B2;
|
||||
this._h[4] = this._h[0] + B1 + C2;
|
||||
this._h[0] = T;
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -1,72 +0,0 @@
|
||||
// ----- 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"
|
||||
);
|
||||
|
||||
// Replace point addition and doubling algorithms
|
||||
// NIST-P256 is a=-3, we need algorithms for a=0
|
||||
sjcl.ecc.pointJac.prototype.add = function(T) {
|
||||
var S = this;
|
||||
if (S.curve !== T.curve) {
|
||||
throw("sjcl.ecc.add(): Points must be on the same curve to add them!");
|
||||
}
|
||||
|
||||
if (S.isIdentity) {
|
||||
return T.toJac();
|
||||
} else if (T.isIdentity) {
|
||||
return S;
|
||||
}
|
||||
|
||||
var z1z1 = S.z.square();
|
||||
var h = T.x.mul(z1z1).subM(S.x);
|
||||
var s2 = T.y.mul(S.z).mul(z1z1);
|
||||
|
||||
if (h.equals(0)) {
|
||||
if (S.y.equals(T.y.mul(z1z1.mul(S.z)))) {
|
||||
// same point
|
||||
return S.doubl();
|
||||
} else {
|
||||
// inverses
|
||||
return new sjcl.ecc.pointJac(S.curve);
|
||||
}
|
||||
}
|
||||
|
||||
var hh = h.square();
|
||||
var i = hh.copy().doubleM().doubleM();
|
||||
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);
|
||||
|
||||
return new sjcl.ecc.pointJac(this.curve,x,y,z);
|
||||
};
|
||||
|
||||
sjcl.ecc.pointJac.prototype.doubl = function () {
|
||||
if (this.isIdentity) { return this; }
|
||||
|
||||
var a = this.x.square();
|
||||
var b = this.y.square();
|
||||
var c = b.square();
|
||||
var d = this.x.add(b).square().subM(a).subM(c).doubleM();
|
||||
var e = a.mul(3);
|
||||
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.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()))
|
||||
};
|
||||
@@ -1,38 +0,0 @@
|
||||
sjcl.ecc.ecdsa.secretKey.prototype.sign = function(hash, paranoia, k_for_testing) {
|
||||
var R = this._curve.r,
|
||||
l = R.bitLength();
|
||||
|
||||
// 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;
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -1,96 +0,0 @@
|
||||
JSDOCSTYLE= codeview
|
||||
JSDOCDIR= jsdoc_toolkit-2.3.3-beta
|
||||
JSDOC= $(JSDOCDIR)/jsrun.sh
|
||||
JSTEMPLATEDIR= $(JSDOCDIR)/templates/$(JSDOCSTYLE)/
|
||||
|
||||
YUICOMPRESSOR= yuicompressor-2.4.2.jar
|
||||
|
||||
include config.mk
|
||||
|
||||
.PHONY: all test test_yui test_closure test_uncompressed lint compression_stats
|
||||
|
||||
all: sjcl.js
|
||||
|
||||
sjcl.js: $(COMPRESS)
|
||||
cp $^ $@
|
||||
|
||||
core.js: $(SOURCES) config.mk
|
||||
cat $(SOURCES) > $@
|
||||
|
||||
# compressed targets
|
||||
core_closure.js: core.js compress/compress_with_closure.sh compress/*.pl
|
||||
compress/compress_with_closure.sh $< > $@
|
||||
|
||||
core_yui.js: core.js compress/compress_with_yui.sh compress/*.pl
|
||||
compress/compress_with_yui.sh $< > $@
|
||||
|
||||
compression_stats: core.js core_closure.js core_yui.js
|
||||
gzip -c core.js > core.js.gz
|
||||
gzip -c core_yui.js > core_yui.js.gz
|
||||
gzip -c core_closure.js > core_closure.js.gz
|
||||
|
||||
@echo
|
||||
@echo
|
||||
@echo Compression stats:
|
||||
@echo
|
||||
@wc -c core.js core_closure.js core_yui.js | head -n -1
|
||||
@echo
|
||||
@wc -c core*.js.gz | head -n -1
|
||||
@echo
|
||||
@echo
|
||||
|
||||
rm -f core*.js.gz
|
||||
|
||||
doc: $(SOURCES)
|
||||
rm -fr $@
|
||||
JSDOCDIR=$(JSDOCDIR) $(JSDOC) -t=$(JSTEMPLATEDIR) $(SOURCES) -d=$@
|
||||
|
||||
doc_private: $(SOURCES)
|
||||
rm -fr $@
|
||||
JSDOCDIR=$(JSDOCDIR) $(JSDOC) -t=$(JSTEMPLATEDIR) $(SOURCES) --private -d=$@
|
||||
|
||||
lint: core.js core/*.js test/*.js browserTest/*.js lint/coding_guidelines.pl
|
||||
rhino lint/jslint_rhino.js core.js
|
||||
lint/coding_guidelines.pl core/*.js test/*.js browserTest/*.js
|
||||
|
||||
|
||||
TEST_COMMON= browserTest/rhinoUtil.js test/test.js
|
||||
|
||||
TEST_SCRIPTS= $(TEST_COMMON) \
|
||||
test/aes_vectors.js test/aes_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 \
|
||||
test/gcm_vectors.js test/gcm_test.js \
|
||||
test/sha256_vectors.js test/sha256_test.js \
|
||||
test/sha256_test_brute_force.js \
|
||||
test/sha512_vectors.js test/sha512_test.js \
|
||||
test/sha512_test_brute_force.js \
|
||||
test/sha1_vectors.js test/sha1_test.js \
|
||||
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_SCRIPTS_OPT= $(TEST_COMMON) \
|
||||
test/srp_vectors.js test/srp_test.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)
|
||||
|
||||
tidy:
|
||||
find . -name '*~' -delete
|
||||
rm -f core.js core_*.js
|
||||
|
||||
clean: tidy
|
||||
rm -fr sjcl.js doc doc_private
|
||||
|
||||
distclean: clean
|
||||
./configure
|
||||
make sjcl.js tidy
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
SJCL used to be in the public domain. Now it's:
|
||||
|
||||
Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh, Stanford University.
|
||||
|
||||
This is for liability reasons. (Speaking of which, SJCL comes with NO
|
||||
WARRANTY WHATSOEVER, express or implied, to the limit of applicable
|
||||
law.)
|
||||
|
||||
SJCL is dual-licensed under the GNU GPL version 2.0 or higher, and a
|
||||
2-clause BSD license. You may use SJCL under the terms of either of
|
||||
these licenses. For your convenience, the GPL versions 2.0 and 3.0
|
||||
and the 2-clause BSD license are included here. Additionally, you may
|
||||
serve "crunched" copies of sjcl (i.e. those with comments removed,
|
||||
and other transformations to reduce code size) without any copyright
|
||||
notice.
|
||||
|
||||
SJCL includes JsDoc toolkit, YUI compressor, Closure compressor,
|
||||
JSLint and the CodeView template in its build system. These programs'
|
||||
copyrights are owned by other people. They are distributed here under
|
||||
the MPL, MIT, BSD, Apache and JSLint licenses. Codeview is "free for
|
||||
download" but has no license attached; it is Copyright 2010 Wouter Bos.
|
||||
|
||||
The BSD license is (almost?) strictly more permissive, but the
|
||||
additionally licensing under the GPL allows us to use OCB 2.0 code
|
||||
royalty-free (at least, if OCB 2.0's creator Phil Rogaway has anything
|
||||
to say about it). Note that if you redistribute SJCL under a license
|
||||
other than the GPL, you or your users may need to pay patent licensing
|
||||
fees for OCB 2.0.
|
||||
|
||||
There may be patents which apply to SJCL other than Phil Rogaway's OCB
|
||||
patents. We suggest that you consult legal counsel before using SJCL
|
||||
in a commercial project.
|
||||
@@ -1,36 +0,0 @@
|
||||
SJCL comes with a file sjcl.js pre-built. This default build includes
|
||||
all the modules except for sjcl.codec.bytes (because the demo site doesn't
|
||||
use it). All you need to do to install is copy this file to your web
|
||||
server and start using it.
|
||||
|
||||
SJCL is divided into modules implementing various cryptographic and
|
||||
convenience functions. If you don't need them all for your application,
|
||||
you can reconfigure SJCL for a smaller code size. To do this, you can
|
||||
run
|
||||
|
||||
./configure --without-all --with-aes --with-sha256 ...
|
||||
|
||||
Then type
|
||||
|
||||
make
|
||||
|
||||
to rebuild sjcl.js. This will also create a few intermediate files
|
||||
core*.js; you can delete these automatically by typing
|
||||
|
||||
make sjcl.js tidy
|
||||
|
||||
instead. You will need make, perl, bash and java to rebuild SJCL.
|
||||
|
||||
Some of the modules depend on other modules; configure should handle this
|
||||
automatically unless you tell it --without-FOO --with-BAR, where BAR
|
||||
depends on FOO. If you do this, configure will yell at you.
|
||||
|
||||
SJCL is compressed by stripping comments, shortening variable names, etc.
|
||||
You can also pass a --compress argument to configure to change the
|
||||
compressor. By default SJCL uses some perl/sh scripts and Google's
|
||||
Closure compressor.
|
||||
|
||||
If you reconfigure SJCL, it is recommended that you run the included test
|
||||
suite by typing "make test". If this prints "FAIL" or segfaults, SJCL
|
||||
doesn't work; please file a bug.
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
|
||||
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
||||
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
The views and conclusions contained in the software and documentation
|
||||
are those of the authors and should not be interpreted as representing
|
||||
official policies, either expressed or implied, of the authors.
|
||||
@@ -1,339 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -1,16 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<title>SJCL browser test</title>
|
||||
<link rel="stylesheet" type="text/css" href="test.css"/>
|
||||
<script type="text/javascript" src="browserUtil.js"></script>
|
||||
<script type="text/javascript" src="../test/run_tests_browser.js"></script>
|
||||
</head>
|
||||
<body onload="testCores(['sjcl.js'])">
|
||||
<h1>SJCL browser test</h1>
|
||||
<div id="status">Waiting for tests to begin...</div>
|
||||
<div id="print"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,133 +0,0 @@
|
||||
browserUtil = {};
|
||||
|
||||
browserUtil.isRhino = (typeof(window) === 'undefined');
|
||||
|
||||
/**
|
||||
* Pause (for the graphics to update and the script timer to clear), then run the
|
||||
* specified action.
|
||||
*/
|
||||
browserUtil.pauseAndThen = function (cb) {
|
||||
cb && window.setTimeout(cb, 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterate using continuation-passing style.
|
||||
*/
|
||||
browserUtil.cpsIterate = function (f, start, end, pause, callback) {
|
||||
var pat = pause ? browserUtil.pauseAndThen : function (cb) { cb && cb(); };
|
||||
function go() {
|
||||
var called = false;
|
||||
if (start >= end) {
|
||||
pat(callback);
|
||||
} else {
|
||||
pat(function () { f(start, function () {
|
||||
if (!called) { called = true; start++; go(); }
|
||||
}); });
|
||||
}
|
||||
}
|
||||
go (start);
|
||||
};
|
||||
|
||||
/**
|
||||
* Map a function over an array using continuation-passing style.
|
||||
*/
|
||||
browserUtil.cpsMap = function (map, list, pause, callback) {
|
||||
browserUtil.cpsIterate(function (i, cb) { map(list[i], i, list.length, cb); },
|
||||
0, list.length, pause, callback);
|
||||
}
|
||||
|
||||
/** Cache for remotely loaded scripts. */
|
||||
browserUtil.scriptCache = {}
|
||||
|
||||
/** Load several scripts, then call back */
|
||||
browserUtil.loadScripts = function(scriptNames, cbSuccess, cbError) {
|
||||
var head = document.getElementsByTagName('head')[0];
|
||||
browserUtil.cpsMap(function (script, i, n, cb) {
|
||||
var scriptE = document.createElement('script'), xhr, loaded = false;
|
||||
|
||||
browserUtil.status("Loading script " + script);
|
||||
|
||||
if (window.location.protocol === "file:") {
|
||||
/* Can't make an AJAX request for files.
|
||||
* But, we know the load time will be short, so timeout-based error
|
||||
* detection is fine.
|
||||
*/
|
||||
scriptE.onload = function () {
|
||||
loaded = true;
|
||||
cb();
|
||||
};
|
||||
scriptE.onerror = function(err) {
|
||||
cbError && cbError(script, err, cb);
|
||||
};
|
||||
script.onreadystatechange = function() {
|
||||
if (this.readyState == 'complete' || this.readyState == 'loaded') {
|
||||
loaded = true;
|
||||
cb();
|
||||
}
|
||||
};
|
||||
scriptE.type = 'text/javascript';
|
||||
scriptE.src = script+"?"+(new Date().valueOf());
|
||||
window.setTimeout(function () {
|
||||
loaded || cbError && cbError(script, "timeout expired", cb);
|
||||
}, 100);
|
||||
head.appendChild(scriptE);
|
||||
} else if (browserUtil.scriptCache[script] !== undefined) {
|
||||
try {
|
||||
scriptE.appendChild(document.createTextNode(browserUtil.scriptCache[script]));
|
||||
} catch (e) {
|
||||
scriptE.text = browserUtil.scriptCache[script];
|
||||
}
|
||||
head.appendChild(scriptE);
|
||||
cb();
|
||||
} else {
|
||||
var xhr;
|
||||
if (window.XMLHttpRequest) {
|
||||
xhr = new XMLHttpRequest;
|
||||
} else if (window.ActiveXObject) {
|
||||
xhr = new ActiveXObject("Microsoft.XMLHTTP");
|
||||
}
|
||||
xhr.onreadystatechange = function() {
|
||||
if (xhr.readyState == 4) {
|
||||
if (xhr.status == 200) {
|
||||
browserUtil.scriptCache[script] = xhr.responseText;
|
||||
try {
|
||||
scriptE.appendChild(document.createTextNode(xhr.responseText));
|
||||
} catch (e) {
|
||||
scriptE.text = xhr.responseText;
|
||||
}
|
||||
head.appendChild(scriptE);
|
||||
cb();
|
||||
} else {
|
||||
cbError && cbError(script, xhr.status, cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
xhr.open("GET", script+"?"+(new Date().valueOf()), true);
|
||||
xhr.send();
|
||||
}
|
||||
}, scriptNames, false, cbSuccess);
|
||||
};
|
||||
|
||||
/** Write a message to the console */
|
||||
browserUtil.write = function(type, message) {
|
||||
var d1 = document.getElementById("print"), d2 = document.createElement("div"), d3 = document.createElement("div");
|
||||
d3.className = type;
|
||||
d3.appendChild(document.createTextNode(message));
|
||||
d2.appendChild(d3);
|
||||
d1.appendChild(d2);
|
||||
return { update: function (type2, message2) {
|
||||
var d4 = document.createElement("div");
|
||||
d4.className = type2 + " also";
|
||||
d4.appendChild(document.createTextNode(message2));
|
||||
d2.insertBefore(d4, d3);
|
||||
}};
|
||||
};
|
||||
|
||||
/** Write a newline. Does nothing in the browser. */
|
||||
browserUtil.writeNewline = function () { };
|
||||
|
||||
/** Write a message to the status line */
|
||||
browserUtil.status = function(message) {
|
||||
var d1 = document.getElementById("status");
|
||||
d1.replaceChild(document.createTextNode(message), d1.firstChild);
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
browserUtil = {
|
||||
isRhino: 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) {
|
||||
print(message);
|
||||
return { update: function (type2, message2) {
|
||||
if (type2 === 'pass') { print(" + " + message2); }
|
||||
else if (type2 === 'unimplemented') { print(" ? " + message2); }
|
||||
else { print(" - " + message2); }
|
||||
}};
|
||||
},
|
||||
|
||||
writeNewline: function () { print(""); },
|
||||
|
||||
status: function(message) {}
|
||||
};
|
||||
@@ -1,59 +0,0 @@
|
||||
* {
|
||||
margin: 0px;
|
||||
padding: 0px;
|
||||
font-family: Arial, Helvetica, FreeSans, sans;
|
||||
}
|
||||
|
||||
#print {
|
||||
position: relative;
|
||||
width: 40em;
|
||||
margin: 0px auto;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#print div {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.pass { color: #0A0; }
|
||||
.fail { color: #A00; }
|
||||
.unimplemented { color: #F80; }
|
||||
|
||||
.begin {
|
||||
text-align: center;
|
||||
padding-bottom: 2px;
|
||||
border-bottom: 1px solid #aaa;
|
||||
margin: 0px auto 2px auto;
|
||||
}
|
||||
|
||||
.all {
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
*+* > .begin, *+* > .all {
|
||||
margin-top: 1em;
|
||||
}
|
||||
|
||||
.also {
|
||||
float: right;
|
||||
width: 17em;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
background: #8A0000;
|
||||
padding: 5px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#status {
|
||||
padding: 3px 10px 3px 5px;
|
||||
background: #d5c490;
|
||||
color: #444;
|
||||
font-size: 0.8em;
|
||||
margin-bottom: 1em;
|
||||
height: 1.3em;
|
||||
vertical-align: middle;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "sjcl",
|
||||
"version": "1.0.0",
|
||||
"main": ["./sjcl.js"]
|
||||
}
|
||||
Binary file not shown.
@@ -1,15 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=`dirname $0`
|
||||
|
||||
$DIR/remove_constants.pl $1 | $DIR/opacify.pl > ._tmpRC.js
|
||||
|
||||
echo -n '"use strict";'
|
||||
java -jar $DIR/compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS \
|
||||
--js ._tmpRC.js \
|
||||
| $DIR/digitize.pl \
|
||||
| $DIR/dewindowize.pl
|
||||
|
||||
|
||||
rm -f ._tmpRC.js
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Compress $1 with YUI Compressor 2.4.2, returning the compressed script on stdout
|
||||
|
||||
DIR=`dirname $0`
|
||||
|
||||
$DIR/remove_constants.pl $1 > ._tmpRC.js
|
||||
|
||||
java -jar $DIR/yuicompressor-2.4.2.jar ._tmpRC.js \
|
||||
| $DIR/digitize.pl
|
||||
|
||||
rm -f ._tmpRC.js
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
|
||||
while (<>) {
|
||||
s/window\.sjcl\s*=/var sjcl=/g;
|
||||
s/window\.sjcl/sjcl/g;
|
||||
print;
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
|
||||
# Convert numbers to hex, when doing so is likely to increase compressibility.
|
||||
# This actually makes the script slightly longer, but generally makes it compress
|
||||
# to something shorter.
|
||||
#
|
||||
# Here we're targeting constants like 0xFF, 0xFFFF0000, 0x10101, 0x100000000, etc.
|
||||
|
||||
sub digitize {
|
||||
my $number = shift;
|
||||
if ($number >= 256) {
|
||||
my $nn = `printf "%x" $number`;
|
||||
if ($nn =~ /^[01f]+$/i) { return "0x$nn"; }
|
||||
}
|
||||
return $number;
|
||||
}
|
||||
|
||||
while (<>) {
|
||||
s/([^a-zA-Z0-9_])(\d+)/$1 . digitize $2/eg;
|
||||
print;
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
|
||||
# This script is a hack.
|
||||
#
|
||||
# Opacify all non-private names by turning them into strings.
|
||||
# That way, the Google compressor won't rename them.
|
||||
#
|
||||
# The script ignores properties whose names begin with _, because they
|
||||
# are believed to be private.
|
||||
#
|
||||
# XXX TODO FIXME: this messes with strings, so it screws up exceptions.
|
||||
|
||||
my $script = join '', <>;
|
||||
|
||||
# remove comments
|
||||
#$script =~ s=/\*([^\*]|\*+[^\/])*\*/==g;
|
||||
#$script =~ s=//.*==g;
|
||||
|
||||
# stringify property names
|
||||
$script =~ s=\.([a-zA-Z][_a-zA-Z0-9]*)=['$1']=g;
|
||||
|
||||
# destringify 'prototype'
|
||||
$script =~ s=\['prototype'\]=.prototype=g;
|
||||
|
||||
# stringify sjcl
|
||||
$script =~ s=(?:var\s+)?sjcl(\.|\s*\=)=window['sjcl']$1=g;
|
||||
|
||||
# stringify object notation
|
||||
$script =~ s=([\{,]
|
||||
\s*
|
||||
(?:/\*(?:[^\*]|\*+[^\/])*\*/\s* # preserve C-style comments
|
||||
|//[^\n]*\n\s*)*)
|
||||
([a-zA-Z0-9][_a-zA-Z0-9]*):=$1'$2':=xg;
|
||||
|
||||
# Export sjcl. This is a bit of a hack, and might get replaced later.
|
||||
print $script;
|
||||
|
||||
# not necessary with windowization.
|
||||
# print "window\['sjcl'\] = sjcl;\n";
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
|
||||
# This script is a hack. It identifies things which it believes to be
|
||||
# constant, then replaces them throughout the code.
|
||||
#
|
||||
# Constants are identified as properties declared in object notation
|
||||
# with values consisting only of capital letters and underscores. If
|
||||
# the first character is an underscore, the constant is private, and
|
||||
# can be removed entirely.
|
||||
#
|
||||
# The script dies if any two constants have the same property name but
|
||||
# different values.
|
||||
my $script = join '', <>;
|
||||
|
||||
# remove comments
|
||||
#$script =~ s=/\*([^\*]|\*+[^\/])*\*/==g;
|
||||
#$script =~ s=//.*==g;
|
||||
|
||||
sub preserve {
|
||||
my $stuff = shift;
|
||||
$stuff =~ s/,//;
|
||||
return $stuff;
|
||||
}
|
||||
|
||||
my %constants = ();
|
||||
|
||||
sub add_constant {
|
||||
my ($name, $value) = @_;
|
||||
if (defined $constants{$name} && $constants{$name} ne $value) {
|
||||
print STDERR "variant constant $name = $value";
|
||||
die;
|
||||
} else {
|
||||
$constants{$name} = $value;
|
||||
#print STDERR "constant: $name = $value\n";
|
||||
}
|
||||
}
|
||||
|
||||
# find private constants
|
||||
while ($script =~
|
||||
s/([,\{]) \s* # indicator that this is part of an object
|
||||
(_[A-Z0-9_]+) \s* : \s* # all-caps variable name beginning with _
|
||||
(\d+|0x[0-9A-Fa-f]+) \s* # numeric value
|
||||
([,\}]) # next part of object
|
||||
/preserve "$1$4"/ex) {
|
||||
add_constant $2, $3;
|
||||
}
|
||||
|
||||
my $script2 = '';
|
||||
|
||||
# find public constants
|
||||
while ($script =~
|
||||
s/^(.*?) # beginning of script
|
||||
([,\{]) \s* # indicator that this is part of an object
|
||||
([A-Z0-9_]+) \s* : \s* # all-caps variable name
|
||||
(\d+|0x[0-9A-Fa-f]+) \s* # numeric value
|
||||
([,\}]) # next part of object([,\{]) \s*
|
||||
/$5/esx) {
|
||||
$script2 .= "$1$2$3:$4";
|
||||
add_constant $3, $4;
|
||||
}
|
||||
|
||||
$script = "$script2$script";
|
||||
|
||||
foreach (keys %constants) {
|
||||
my $value = $constants{$_};
|
||||
$script =~ s/(?:[a-zA-Z0-9_]+\.)+$_(?=[^a-zA-Z0-9_])/$value/g;
|
||||
}
|
||||
|
||||
print $script;
|
||||
Binary file not shown.
@@ -1,2 +0,0 @@
|
||||
SOURCES= core/sjcl.js core/aes.js core/bitArray.js core/codecString.js core/codecHex.js core/codecBase64.js core/sha256.js core/ccm.js core/ocb2.js core/gcm.js core/hmac.js core/pbkdf2.js core/random.js core/convenience.js
|
||||
COMPRESS= core_closure.js
|
||||
143
src/js/sjcl/configure
vendored
143
src/js/sjcl/configure
vendored
@@ -1,143 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
|
||||
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 %deps = ('aes'=>'sjcl',
|
||||
'bitArray'=>'sjcl',
|
||||
'codecString'=>'bitArray',
|
||||
'codecHex'=>'bitArray',
|
||||
'codecBase64'=>'bitArray',
|
||||
'codecBytes'=>'bitArray',
|
||||
'sha256'=>'codecString',
|
||||
'sha512'=>'codecString',
|
||||
'sha1'=>'codecString',
|
||||
'ccm'=>'bitArray,aes',
|
||||
'ocb2'=>'bitArray,aes',
|
||||
'gcm'=>'bitArray,aes',
|
||||
'hmac'=>'sha256',
|
||||
'pbkdf2'=>'hmac',
|
||||
'srp'=>'sha1,bn,bitArray',
|
||||
'bn'=>'bitArray,random',
|
||||
'ecc'=>'bn',
|
||||
'cbc'=>'bitArray,aes',
|
||||
'random'=>'sha256,aes',
|
||||
'convenience'=>'ccm,pbkdf2,random,codecBase64');
|
||||
|
||||
my $compress = "closure";
|
||||
|
||||
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/);
|
||||
|
||||
# argument parsing
|
||||
while ($arg = shift @ARGV) {
|
||||
if ($arg =~ /^--?with-all$/) {
|
||||
foreach (@targets) {
|
||||
if ($enabled{$_} == 0) {
|
||||
$enabled{$_} = 1;
|
||||
}
|
||||
}
|
||||
} elsif ($arg =~ /^--?without-all$/) {
|
||||
foreach (@targets) {
|
||||
if ($enabled{$_} == 1) {
|
||||
$enabled{$_} = 0;
|
||||
}
|
||||
}
|
||||
} elsif ($arg =~ /^--?with-(.*)$/) {
|
||||
$targ = $1;
|
||||
$targ =~ s/-(.)/uc $1/ge;
|
||||
if (!defined $deps{$targ}) {
|
||||
print STDERR "No such target $targ\n";
|
||||
exit 1;
|
||||
}
|
||||
$enabled{$targ} = 2;
|
||||
} elsif ($arg =~ /^--?without-(.*)$/) {
|
||||
$targ = $1;
|
||||
$targ =~ s/-(.)/uc $1/ge;
|
||||
if (!defined $deps{$targ}) {
|
||||
print STDERR "No such target $targ\n";
|
||||
exit 1;
|
||||
}
|
||||
$enabled{$targ} = -1;
|
||||
} elsif ($arg =~ /^--?compress(?:or|ion)?=(none|closure|yui)$/) {
|
||||
$compress = $1;
|
||||
} else {
|
||||
my $targets = join " ", @targets;
|
||||
$targets =~ s/sjcl //;
|
||||
$targets =~ s/(.{50})\s+/$1\n /g;
|
||||
print STDERR <<EOT;
|
||||
Usage: $0 arguments...
|
||||
|
||||
Valid arguments are:
|
||||
--with-all: by default, include all targets
|
||||
--without-all: by default, include no targets
|
||||
|
||||
--compress=none|closure|yui
|
||||
|
||||
--with-TARGET: require TARGET
|
||||
--without-TARGET: forbid TARGET
|
||||
|
||||
--help: show this message
|
||||
|
||||
Valid targets are:
|
||||
$targets
|
||||
|
||||
EOT
|
||||
exit 1 unless $arg =~ /^--?help$/;
|
||||
exit 0;
|
||||
}
|
||||
}
|
||||
|
||||
my $config = '';
|
||||
my $pconfig;
|
||||
|
||||
# dependency analysis: forbidden
|
||||
foreach $i (@targets) {
|
||||
if ($enabled{$i} > 0) {
|
||||
foreach $j (split /,/, $deps{$i}) {
|
||||
if ($enabled{$j} == -1) {
|
||||
if ($enabled{$i} == 2) {
|
||||
print STDERR "Conflicting options: $i depends on $j\n";
|
||||
exit 1;
|
||||
} else {
|
||||
$enabled{$i} = -1;
|
||||
last;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# reverse
|
||||
foreach $i (reverse @targets) {
|
||||
if ($enabled{$i} > 0) {
|
||||
foreach $j (split /,/, $deps{$i}) {
|
||||
if ($enabled{$j} < $enabled{$i}) {
|
||||
$enabled{$j} = $enabled{$i};
|
||||
}
|
||||
}
|
||||
$config = "$i $config";
|
||||
}
|
||||
}
|
||||
|
||||
open CONFIG, "> config.mk" or die "$!";
|
||||
|
||||
|
||||
($pconfig = $config) =~ s/^sjcl //;
|
||||
$pconfig =~ s/ /\n /g;
|
||||
print "Enabled components:\n $pconfig\n";
|
||||
print "Compression: $compress\n";
|
||||
|
||||
$config =~ s=\S+=core/$&.js=g;
|
||||
print CONFIG "SOURCES= $config\n";
|
||||
|
||||
$compress = "core_$compress.js";
|
||||
$compress = 'core.js' if ($compress eq 'core_none.js');
|
||||
|
||||
print CONFIG "COMPRESS= $compress\n";
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
/** @fileOverview Low-level AES implementation.
|
||||
*
|
||||
* This file contains a low-level implementation of AES, optimized for
|
||||
* size and for efficiency on several browsers. It is based on
|
||||
* OpenSSL's aes_core.c, a public-domain implementation by Vincent
|
||||
* Rijmen, Antoon Bosselaers and Paulo Barreto.
|
||||
*
|
||||
* An older version of this implementation is available in the public
|
||||
* domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
|
||||
* Stanford University 2008-2010 and BSD-licensed for liability
|
||||
* reasons.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/**
|
||||
* Schedule out an AES key for both encryption and decryption. This
|
||||
* is a low-level class. Use a cipher mode to do bulk encryption.
|
||||
*
|
||||
* @constructor
|
||||
* @param {Array} key The key as an array of 4, 6 or 8 words.
|
||||
*
|
||||
* @class Advanced Encryption Standard (low-level interface)
|
||||
*/
|
||||
sjcl.cipher.aes = function (key) {
|
||||
if (!this._tables[0][0][0]) {
|
||||
this._precompute();
|
||||
}
|
||||
|
||||
var i, j, tmp,
|
||||
encKey, decKey,
|
||||
sbox = this._tables[0][4], decTable = this._tables[1],
|
||||
keyLen = key.length, rcon = 1;
|
||||
|
||||
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
|
||||
throw new sjcl.exception.invalid("invalid aes key size");
|
||||
}
|
||||
|
||||
this._key = [encKey = key.slice(0), decKey = []];
|
||||
|
||||
// schedule encryption keys
|
||||
for (i = keyLen; i < 4 * keyLen + 28; i++) {
|
||||
tmp = encKey[i-1];
|
||||
|
||||
// apply sbox
|
||||
if (i%keyLen === 0 || (keyLen === 8 && i%keyLen === 4)) {
|
||||
tmp = sbox[tmp>>>24]<<24 ^ sbox[tmp>>16&255]<<16 ^ sbox[tmp>>8&255]<<8 ^ sbox[tmp&255];
|
||||
|
||||
// shift rows and add rcon
|
||||
if (i%keyLen === 0) {
|
||||
tmp = tmp<<8 ^ tmp>>>24 ^ rcon<<24;
|
||||
rcon = rcon<<1 ^ (rcon>>7)*283;
|
||||
}
|
||||
}
|
||||
|
||||
encKey[i] = encKey[i-keyLen] ^ tmp;
|
||||
}
|
||||
|
||||
// schedule decryption keys
|
||||
for (j = 0; i; j++, i--) {
|
||||
tmp = encKey[j&3 ? i : i - 4];
|
||||
if (i<=4 || j<4) {
|
||||
decKey[j] = tmp;
|
||||
} else {
|
||||
decKey[j] = decTable[0][sbox[tmp>>>24 ]] ^
|
||||
decTable[1][sbox[tmp>>16 & 255]] ^
|
||||
decTable[2][sbox[tmp>>8 & 255]] ^
|
||||
decTable[3][sbox[tmp & 255]];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.cipher.aes.prototype = {
|
||||
// public
|
||||
/* Something like this might appear here eventually
|
||||
name: "AES",
|
||||
blockSize: 4,
|
||||
keySizes: [4,6,8],
|
||||
*/
|
||||
|
||||
/**
|
||||
* Encrypt an array of 4 big-endian words.
|
||||
* @param {Array} data The plaintext.
|
||||
* @return {Array} The ciphertext.
|
||||
*/
|
||||
encrypt:function (data) { return this._crypt(data,0); },
|
||||
|
||||
/**
|
||||
* Decrypt an array of 4 big-endian words.
|
||||
* @param {Array} data The ciphertext.
|
||||
* @return {Array} The plaintext.
|
||||
*/
|
||||
decrypt:function (data) { return this._crypt(data,1); },
|
||||
|
||||
/**
|
||||
* The expanded S-box and inverse S-box tables. These will be computed
|
||||
* on the client so that we don't have to send them down the wire.
|
||||
*
|
||||
* There are two tables, _tables[0] is for encryption and
|
||||
* _tables[1] is for decryption.
|
||||
*
|
||||
* The first 4 sub-tables are the expanded S-box with MixColumns. The
|
||||
* last (_tables[01][4]) is the S-box itself.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_tables: [[[],[],[],[],[]],[[],[],[],[],[]]],
|
||||
|
||||
/**
|
||||
* Expand the S-box tables.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_precompute: function () {
|
||||
var encTable = this._tables[0], decTable = this._tables[1],
|
||||
sbox = encTable[4], sboxInv = decTable[4],
|
||||
i, x, xInv, d=[], th=[], x2, x4, x8, s, tEnc, tDec;
|
||||
|
||||
// Compute double and third tables
|
||||
for (i = 0; i < 256; i++) {
|
||||
th[( d[i] = i<<1 ^ (i>>7)*283 )^i]=i;
|
||||
}
|
||||
|
||||
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
|
||||
// Compute sbox
|
||||
s = xInv ^ xInv<<1 ^ xInv<<2 ^ xInv<<3 ^ xInv<<4;
|
||||
s = s>>8 ^ s&255 ^ 99;
|
||||
sbox[x] = s;
|
||||
sboxInv[s] = x;
|
||||
|
||||
// Compute MixColumns
|
||||
x8 = d[x4 = d[x2 = d[x]]];
|
||||
tDec = x8*0x1010101 ^ x4*0x10001 ^ x2*0x101 ^ x*0x1010100;
|
||||
tEnc = d[s]*0x101 ^ s*0x1010100;
|
||||
|
||||
for (i = 0; i < 4; i++) {
|
||||
encTable[i][x] = tEnc = tEnc<<24 ^ tEnc>>>8;
|
||||
decTable[i][s] = tDec = tDec<<24 ^ tDec>>>8;
|
||||
}
|
||||
}
|
||||
|
||||
// Compactify. Considerable speedup on Firefox.
|
||||
for (i = 0; i < 5; i++) {
|
||||
encTable[i] = encTable[i].slice(0);
|
||||
decTable[i] = decTable[i].slice(0);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Encryption and decryption core.
|
||||
* @param {Array} input Four words to be encrypted or decrypted.
|
||||
* @param dir The direction, 0 for encrypt and 1 for decrypt.
|
||||
* @return {Array} The four encrypted or decrypted words.
|
||||
* @private
|
||||
*/
|
||||
_crypt:function (input, dir) {
|
||||
if (input.length !== 4) {
|
||||
throw new sjcl.exception.invalid("invalid aes block size");
|
||||
}
|
||||
|
||||
var key = this._key[dir],
|
||||
// state variables a,b,c,d are loaded with pre-whitened data
|
||||
a = input[0] ^ key[0],
|
||||
b = input[dir ? 3 : 1] ^ key[1],
|
||||
c = input[2] ^ key[2],
|
||||
d = input[dir ? 1 : 3] ^ key[3],
|
||||
a2, b2, c2,
|
||||
|
||||
nInnerRounds = key.length/4 - 2,
|
||||
i,
|
||||
kIndex = 4,
|
||||
out = [0,0,0,0],
|
||||
table = this._tables[dir],
|
||||
|
||||
// load up the tables
|
||||
t0 = table[0],
|
||||
t1 = table[1],
|
||||
t2 = table[2],
|
||||
t3 = table[3],
|
||||
sbox = table[4];
|
||||
|
||||
// Inner rounds. Cribbed from OpenSSL.
|
||||
for (i = 0; i < nInnerRounds; i++) {
|
||||
a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];
|
||||
b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
|
||||
c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
|
||||
d = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
|
||||
kIndex += 4;
|
||||
a=a2; b=b2; c=c2;
|
||||
}
|
||||
|
||||
// Last round.
|
||||
for (i = 0; i < 4; i++) {
|
||||
out[dir ? 3&-i : i] =
|
||||
sbox[a>>>24 ]<<24 ^
|
||||
sbox[b>>16 & 255]<<16 ^
|
||||
sbox[c>>8 & 255]<<8 ^
|
||||
sbox[d & 255] ^
|
||||
key[kIndex++];
|
||||
a2=a; a=b; b=c; c=d; d=a2;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
/** @fileOverview Arrays of bits, encoded as arrays of Numbers.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace Arrays of bits, encoded as arrays of Numbers.
|
||||
*
|
||||
* @description
|
||||
* <p>
|
||||
* These objects are the currency accepted by SJCL's crypto functions.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Most of our crypto primitives operate on arrays of 4-byte words internally,
|
||||
* but many of them can take arguments that are not a multiple of 4 bytes.
|
||||
* This library encodes arrays of bits (whose size need not be a multiple of 8
|
||||
* bits) as arrays of 32-bit words. The bits are packed, big-endian, into an
|
||||
* array of words, 32 bits at a time. Since the words are double-precision
|
||||
* floating point numbers, they fit some extra data. We use this (in a private,
|
||||
* possibly-changing manner) to encode the number of bits actually present
|
||||
* in the last word of the array.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Because bitwise ops clear this out-of-band data, these arrays can be passed
|
||||
* to ciphers like AES which want arrays of words.
|
||||
* </p>
|
||||
*/
|
||||
sjcl.bitArray = {
|
||||
/**
|
||||
* Array slices in units of bits.
|
||||
* @param {bitArray} a The array to slice.
|
||||
* @param {Number} bstart The offset to the start of the slice, in bits.
|
||||
* @param {Number} bend The offset to the end of the slice, in bits. If this is undefined,
|
||||
* slice until the end of the array.
|
||||
* @return {bitArray} The requested slice.
|
||||
*/
|
||||
bitSlice: function (a, bstart, bend) {
|
||||
a = sjcl.bitArray._shiftRight(a.slice(bstart/32), 32 - (bstart & 31)).slice(1);
|
||||
return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend-bstart);
|
||||
},
|
||||
|
||||
/**
|
||||
* Extract a number packed into a bit array.
|
||||
* @param {bitArray} a The array to slice.
|
||||
* @param {Number} bstart The offset to the start of the slice, in bits.
|
||||
* @param {Number} length The length of the number to extract.
|
||||
* @return {Number} The requested slice.
|
||||
*/
|
||||
extract: function(a, bstart, blength) {
|
||||
// FIXME: this Math.floor is not necessary at all, but for some reason
|
||||
// seems to suppress a bug in the Chromium JIT.
|
||||
var x, sh = Math.floor((-bstart-blength) & 31);
|
||||
if ((bstart + blength - 1 ^ bstart) & -32) {
|
||||
// it crosses a boundary
|
||||
x = (a[bstart/32|0] << (32 - sh)) ^ (a[bstart/32+1|0] >>> sh);
|
||||
} else {
|
||||
// within a single word
|
||||
x = a[bstart/32|0] >>> sh;
|
||||
}
|
||||
return x & ((1<<blength) - 1);
|
||||
},
|
||||
|
||||
/**
|
||||
* Concatenate two bit arrays.
|
||||
* @param {bitArray} a1 The first array.
|
||||
* @param {bitArray} a2 The second array.
|
||||
* @return {bitArray} The concatenation of a1 and a2.
|
||||
*/
|
||||
concat: function (a1, a2) {
|
||||
if (a1.length === 0 || a2.length === 0) {
|
||||
return a1.concat(a2);
|
||||
}
|
||||
|
||||
var out, i, last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);
|
||||
if (shift === 32) {
|
||||
return a1.concat(a2);
|
||||
} else {
|
||||
return sjcl.bitArray._shiftRight(a2, shift, last|0, a1.slice(0,a1.length-1));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Find the length of an array of bits.
|
||||
* @param {bitArray} a The array.
|
||||
* @return {Number} The length of a, in bits.
|
||||
*/
|
||||
bitLength: function (a) {
|
||||
var l = a.length, x;
|
||||
if (l === 0) { return 0; }
|
||||
x = a[l - 1];
|
||||
return (l-1) * 32 + sjcl.bitArray.getPartial(x);
|
||||
},
|
||||
|
||||
/**
|
||||
* Truncate an array.
|
||||
* @param {bitArray} a The array.
|
||||
* @param {Number} len The length to truncate to, in bits.
|
||||
* @return {bitArray} A new array, truncated to len bits.
|
||||
*/
|
||||
clamp: function (a, len) {
|
||||
if (a.length * 32 < len) { return a; }
|
||||
a = a.slice(0, Math.ceil(len / 32));
|
||||
var l = a.length;
|
||||
len = len & 31;
|
||||
if (l > 0 && len) {
|
||||
a[l-1] = sjcl.bitArray.partial(len, a[l-1] & 0x80000000 >> (len-1), 1);
|
||||
}
|
||||
return a;
|
||||
},
|
||||
|
||||
/**
|
||||
* Make a partial word for a bit array.
|
||||
* @param {Number} len The number of bits in the word.
|
||||
* @param {Number} x The bits.
|
||||
* @param {Number} [0] _end Pass 1 if x has already been shifted to the high side.
|
||||
* @return {Number} The partial word.
|
||||
*/
|
||||
partial: function (len, x, _end) {
|
||||
if (len === 32) { return x; }
|
||||
return (_end ? x|0 : x << (32-len)) + len * 0x10000000000;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the number of bits used by a partial word.
|
||||
* @param {Number} x The partial word.
|
||||
* @return {Number} The number of bits used by the partial word.
|
||||
*/
|
||||
getPartial: function (x) {
|
||||
return Math.round(x/0x10000000000) || 32;
|
||||
},
|
||||
|
||||
/**
|
||||
* Compare two arrays for equality in a predictable amount of time.
|
||||
* @param {bitArray} a The first array.
|
||||
* @param {bitArray} b The second array.
|
||||
* @return {boolean} true if a == b; false otherwise.
|
||||
*/
|
||||
equal: function (a, b) {
|
||||
if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) {
|
||||
return false;
|
||||
}
|
||||
var x = 0, i;
|
||||
for (i=0; i<a.length; i++) {
|
||||
x |= a[i]^b[i];
|
||||
}
|
||||
return (x === 0);
|
||||
},
|
||||
|
||||
/** Shift an array right.
|
||||
* @param {bitArray} a The array to shift.
|
||||
* @param {Number} shift The number of bits to shift.
|
||||
* @param {Number} [carry=0] A byte to carry in
|
||||
* @param {bitArray} [out=[]] An array to prepend to the output.
|
||||
* @private
|
||||
*/
|
||||
_shiftRight: function (a, shift, carry, out) {
|
||||
var i, last2=0, shift2;
|
||||
if (out === undefined) { out = []; }
|
||||
|
||||
for (; shift >= 32; shift -= 32) {
|
||||
out.push(carry);
|
||||
carry = 0;
|
||||
}
|
||||
if (shift === 0) {
|
||||
return out.concat(a);
|
||||
}
|
||||
|
||||
for (i=0; i<a.length; i++) {
|
||||
out.push(carry | a[i]>>>shift);
|
||||
carry = a[i] << (32-shift);
|
||||
}
|
||||
last2 = a.length ? a[a.length-1] : 0;
|
||||
shift2 = sjcl.bitArray.getPartial(last2);
|
||||
out.push(sjcl.bitArray.partial(shift+shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(),1));
|
||||
return out;
|
||||
},
|
||||
|
||||
/** xor a block of 4 words together.
|
||||
* @private
|
||||
*/
|
||||
_xor4: function(x,y) {
|
||||
return [x[0]^y[0],x[1]^y[1],x[2]^y[2],x[3]^y[3]];
|
||||
}
|
||||
};
|
||||
@@ -1,552 +0,0 @@
|
||||
/**
|
||||
* @constructor
|
||||
* Constructs a new bignum from another bignum, a number or a hex string.
|
||||
*/
|
||||
sjcl.bn = function(it) {
|
||||
this.initWith(it);
|
||||
};
|
||||
|
||||
sjcl.bn.prototype = {
|
||||
radix: 24,
|
||||
maxMul: 8,
|
||||
_class: sjcl.bn,
|
||||
|
||||
copy: function() {
|
||||
return new this._class(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Initializes this with it, either as a bn, a number, or a hex string.
|
||||
*/
|
||||
initWith: function(it) {
|
||||
var i=0, k, n, l;
|
||||
switch(typeof it) {
|
||||
case "object":
|
||||
this.limbs = it.limbs.slice(0);
|
||||
break;
|
||||
|
||||
case "number":
|
||||
this.limbs = [it];
|
||||
this.normalize();
|
||||
break;
|
||||
|
||||
case "string":
|
||||
it = it.replace(/^0x/, '');
|
||||
this.limbs = [];
|
||||
// hack
|
||||
k = this.radix / 4;
|
||||
for (i=0; i < it.length; i+=k) {
|
||||
this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i),16));
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
this.limbs = [0];
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if "this" and "that" are equal. Calls fullReduce().
|
||||
* Equality test is in constant time.
|
||||
*/
|
||||
equals: function(that) {
|
||||
if (typeof that === "number") { that = new this._class(that); }
|
||||
var difference = 0, i;
|
||||
this.fullReduce();
|
||||
that.fullReduce();
|
||||
for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) {
|
||||
difference |= this.getLimb(i) ^ that.getLimb(i);
|
||||
}
|
||||
return (difference === 0);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the i'th limb of this, zero if i is too large.
|
||||
*/
|
||||
getLimb: function(i) {
|
||||
return (i >= this.limbs.length) ? 0 : this.limbs[i];
|
||||
},
|
||||
|
||||
/**
|
||||
* Constant time comparison function.
|
||||
* Returns 1 if this >= that, or zero otherwise.
|
||||
*/
|
||||
greaterEquals: function(that) {
|
||||
if (typeof that === "number") { that = new this._class(that); }
|
||||
var less = 0, greater = 0, i, a, b;
|
||||
i = Math.max(this.limbs.length, that.limbs.length) - 1;
|
||||
for (; i>= 0; i--) {
|
||||
a = this.getLimb(i);
|
||||
b = that.getLimb(i);
|
||||
greater |= (b - a) & ~less;
|
||||
less |= (a - b) & ~greater;
|
||||
}
|
||||
return (greater | ~less) >>> 31;
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert to a hex string.
|
||||
*/
|
||||
toString: function() {
|
||||
this.fullReduce();
|
||||
var out="", i, s, l = this.limbs;
|
||||
for (i=0; i < this.limbs.length; i++) {
|
||||
s = l[i].toString(16);
|
||||
while (i < this.limbs.length - 1 && s.length < 6) {
|
||||
s = "0" + s;
|
||||
}
|
||||
out = s + out;
|
||||
}
|
||||
return "0x"+out;
|
||||
},
|
||||
|
||||
/** this += that. Does not normalize. */
|
||||
addM: function(that) {
|
||||
if (typeof(that) !== "object") { that = new this._class(that); }
|
||||
var i, l=this.limbs, ll=that.limbs;
|
||||
for (i=l.length; i<ll.length; i++) {
|
||||
l[i] = 0;
|
||||
}
|
||||
for (i=0; i<ll.length; i++) {
|
||||
l[i] += ll[i];
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/** this *= 2. Requires normalized; ends up normalized. */
|
||||
doubleM: function() {
|
||||
var i, carry=0, tmp, r=this.radix, m=this.radixMask, l=this.limbs;
|
||||
for (i=0; i<l.length; i++) {
|
||||
tmp = l[i];
|
||||
tmp = tmp+tmp+carry;
|
||||
l[i] = tmp & m;
|
||||
carry = tmp >> r;
|
||||
}
|
||||
if (carry) {
|
||||
l.push(carry);
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/** this /= 2, rounded down. Requires normalized; ends up normalized. */
|
||||
halveM: function() {
|
||||
var i, carry=0, tmp, r=this.radix, l=this.limbs;
|
||||
for (i=l.length-1; i>=0; i--) {
|
||||
tmp = l[i];
|
||||
l[i] = (tmp+carry)>>1;
|
||||
carry = (tmp&1) << r;
|
||||
}
|
||||
if (!l[l.length-1]) {
|
||||
l.pop();
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/** this -= that. Does not normalize. */
|
||||
subM: function(that) {
|
||||
if (typeof(that) !== "object") { that = new this._class(that); }
|
||||
var i, l=this.limbs, ll=that.limbs;
|
||||
for (i=l.length; i<ll.length; i++) {
|
||||
l[i] = 0;
|
||||
}
|
||||
for (i=0; i<ll.length; i++) {
|
||||
l[i] -= ll[i];
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
mod: function(that) {
|
||||
var neg = !this.greaterEquals(new sjcl.bn(0));
|
||||
|
||||
that = new sjcl.bn(that).normalize(); // copy before we begin
|
||||
var out = new sjcl.bn(this).normalize(), ci=0;
|
||||
|
||||
if (neg) out = (new sjcl.bn(0)).subM(out).normalize();
|
||||
|
||||
for (; out.greaterEquals(that); ci++) {
|
||||
that.doubleM();
|
||||
}
|
||||
|
||||
if (neg) out = that.sub(out).normalize();
|
||||
|
||||
for (; ci > 0; ci--) {
|
||||
that.halveM();
|
||||
if (out.greaterEquals(that)) {
|
||||
out.subM(that).normalize();
|
||||
}
|
||||
}
|
||||
return out.trim();
|
||||
},
|
||||
|
||||
/** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */
|
||||
inverseMod: function(p) {
|
||||
var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz=1;
|
||||
|
||||
if (!(p.limbs[0] & 1)) {
|
||||
throw (new sjcl.exception.invalid("inverseMod: p must be odd"));
|
||||
}
|
||||
|
||||
// invariant: y is odd
|
||||
do {
|
||||
if (x.limbs[0] & 1) {
|
||||
if (!x.greaterEquals(y)) {
|
||||
// x < y; swap everything
|
||||
tmp = x; x = y; y = tmp;
|
||||
tmp = a; a = b; b = tmp;
|
||||
}
|
||||
x.subM(y);
|
||||
x.normalize();
|
||||
|
||||
if (!a.greaterEquals(b)) {
|
||||
a.addM(p);
|
||||
}
|
||||
a.subM(b);
|
||||
}
|
||||
|
||||
// cut everything in half
|
||||
x.halveM();
|
||||
if (a.limbs[0] & 1) {
|
||||
a.addM(p);
|
||||
}
|
||||
a.normalize();
|
||||
a.halveM();
|
||||
|
||||
// check for termination: x ?= 0
|
||||
for (i=nz=0; i<x.limbs.length; i++) {
|
||||
nz |= x.limbs[i];
|
||||
}
|
||||
} while(nz);
|
||||
|
||||
if (!y.equals(1)) {
|
||||
throw (new sjcl.exception.invalid("inverseMod: p and x must be relatively prime"));
|
||||
}
|
||||
|
||||
return b;
|
||||
},
|
||||
|
||||
/** this + that. Does not normalize. */
|
||||
add: function(that) {
|
||||
return this.copy().addM(that);
|
||||
},
|
||||
|
||||
/** this - that. Does not normalize. */
|
||||
sub: function(that) {
|
||||
return this.copy().subM(that);
|
||||
},
|
||||
|
||||
/** this * that. Normalizes and reduces. */
|
||||
mul: function(that) {
|
||||
if (typeof(that) === "number") { that = new this._class(that); }
|
||||
var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii=this.maxMul;
|
||||
|
||||
for (i=0; i < this.limbs.length + that.limbs.length + 1; i++) {
|
||||
c[i] = 0;
|
||||
}
|
||||
for (i=0; i<al; i++) {
|
||||
ai = a[i];
|
||||
for (j=0; j<bl; j++) {
|
||||
c[i+j] += ai * b[j];
|
||||
}
|
||||
|
||||
if (!--ii) {
|
||||
ii = this.maxMul;
|
||||
out.cnormalize();
|
||||
}
|
||||
}
|
||||
return out.cnormalize().reduce();
|
||||
},
|
||||
|
||||
/** this ^ 2. Normalizes and reduces. */
|
||||
square: function() {
|
||||
return this.mul(this);
|
||||
},
|
||||
|
||||
/** this ^ n. Uses square-and-multiply. Normalizes and reduces. */
|
||||
power: function(l) {
|
||||
if (typeof(l) === "number") {
|
||||
l = [l];
|
||||
} else if (l.limbs !== undefined) {
|
||||
l = l.normalize().limbs;
|
||||
}
|
||||
var i, j, out = new this._class(1), pow = this;
|
||||
|
||||
for (i=0; i<l.length; i++) {
|
||||
for (j=0; j<this.radix; j++) {
|
||||
if (l[i] & (1<<j)) {
|
||||
out = out.mul(pow);
|
||||
}
|
||||
pow = pow.square();
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
/** this * that mod N */
|
||||
mulmod: function(that, N) {
|
||||
return this.mod(N).mul(that.mod(N)).mod(N);
|
||||
},
|
||||
|
||||
/** this ^ x mod N */
|
||||
powermod: function(x, N) {
|
||||
var result = new sjcl.bn(1), a = new sjcl.bn(this), k = new sjcl.bn(x);
|
||||
while (true) {
|
||||
if (k.limbs[0] & 1) { result = result.mulmod(a, N); }
|
||||
k.halveM();
|
||||
if (k.equals(0)) { break; }
|
||||
a = a.mulmod(a, N);
|
||||
}
|
||||
return result.normalize().reduce();
|
||||
},
|
||||
|
||||
trim: function() {
|
||||
var l = this.limbs, p;
|
||||
do {
|
||||
p = l.pop();
|
||||
} while (l.length && p === 0);
|
||||
l.push(p);
|
||||
return this;
|
||||
},
|
||||
|
||||
/** Reduce mod a modulus. Stubbed for subclassing. */
|
||||
reduce: function() {
|
||||
return this;
|
||||
},
|
||||
|
||||
/** Reduce and normalize. */
|
||||
fullReduce: function() {
|
||||
return this.normalize();
|
||||
},
|
||||
|
||||
/** Propagate carries. */
|
||||
normalize: function() {
|
||||
var carry=0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
|
||||
for (i=0; i < ll || (carry !== 0 && carry !== -1); i++) {
|
||||
l = (limbs[i]||0) + carry;
|
||||
m = limbs[i] = l & mask;
|
||||
carry = (l-m)*ipv;
|
||||
}
|
||||
if (carry === -1) {
|
||||
limbs[i-1] -= this.placeVal;
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/** Constant-time normalize. Does not allocate additional space. */
|
||||
cnormalize: function() {
|
||||
var carry=0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
|
||||
for (i=0; i < ll-1; i++) {
|
||||
l = limbs[i] + carry;
|
||||
m = limbs[i] = l & mask;
|
||||
carry = (l-m)*ipv;
|
||||
}
|
||||
limbs[i] += carry;
|
||||
return this;
|
||||
},
|
||||
|
||||
/** Serialize to a bit array */
|
||||
toBits: function(len) {
|
||||
this.fullReduce();
|
||||
len = len || this.exponent || this.bitLength();
|
||||
var i = Math.floor((len-1)/24), w=sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix,
|
||||
out = [w.partial(e, this.getLimb(i))];
|
||||
for (i--; i >= 0; i--) {
|
||||
out = w.concat(out, [w.partial(Math.min(this.radix,len), this.getLimb(i))]);
|
||||
len -= this.radix;
|
||||
}
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Return the length in bits, rounded up to the nearest byte. */
|
||||
bitLength: function() {
|
||||
this.fullReduce();
|
||||
var out = this.radix * (this.limbs.length - 1),
|
||||
b = this.limbs[this.limbs.length - 1];
|
||||
for (; b; b >>>= 1) {
|
||||
out ++;
|
||||
}
|
||||
return out+7 & -8;
|
||||
}
|
||||
};
|
||||
|
||||
/** @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;
|
||||
|
||||
words[0] = w.extract(bits, 0, e);
|
||||
for (; e < l; e += t.radix) {
|
||||
words.unshift(w.extract(bits, e, t.radix));
|
||||
}
|
||||
|
||||
out.limbs = words;
|
||||
return out;
|
||||
};
|
||||
|
||||
|
||||
|
||||
sjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2,sjcl.bn.prototype.radix));
|
||||
sjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;
|
||||
|
||||
/**
|
||||
* Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,
|
||||
* 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 */
|
||||
function p(it) {
|
||||
this.initWith(it);
|
||||
/*if (this.limbs[this.modOffset]) {
|
||||
this.reduce();
|
||||
}*/
|
||||
}
|
||||
|
||||
var ppr = p.prototype = new sjcl.bn(), i, tmp, mo;
|
||||
mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);
|
||||
ppr.exponent = exponent;
|
||||
ppr.offset = [];
|
||||
ppr.factor = [];
|
||||
ppr.minOffset = mo;
|
||||
ppr.fullMask = 0;
|
||||
ppr.fullOffset = [];
|
||||
ppr.fullFactor = [];
|
||||
ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2,exponent));
|
||||
|
||||
ppr.fullMask = 0|-Math.pow(2, exponent % ppr.radix);
|
||||
|
||||
for (i=0; i<coeff.length; i++) {
|
||||
ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);
|
||||
ppr.fullOffset[i] = Math.ceil(coeff[i][0] / ppr.radix - tmp);
|
||||
ppr.factor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);
|
||||
ppr.fullFactor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);
|
||||
ppr.modulus.addM(new sjcl.bn(Math.pow(2,coeff[i][0])*coeff[i][1]));
|
||||
ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative
|
||||
}
|
||||
ppr._class = p;
|
||||
ppr.modulus.cnormalize();
|
||||
|
||||
/** Approximate reduction mod p. May leave a number which is negative or slightly larger than p.
|
||||
* @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;
|
||||
|
||||
i = this.minOffset;
|
||||
while (limbs.length > mo) {
|
||||
l = limbs.pop();
|
||||
ll = limbs.length;
|
||||
for (k=0; k<ol; k++) {
|
||||
limbs[ll+off[k]] -= fac[k] * l;
|
||||
}
|
||||
|
||||
i--;
|
||||
if (!i) {
|
||||
limbs.push(0);
|
||||
this.cnormalize();
|
||||
i = this.minOffset;
|
||||
}
|
||||
}
|
||||
this.cnormalize();
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/** @this {sjcl.bn} */
|
||||
ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function() {
|
||||
var limbs = this.limbs, i = limbs.length - 1, k, l;
|
||||
this.reduce();
|
||||
if (i === this.modOffset - 1) {
|
||||
l = limbs[i] & this.fullMask;
|
||||
limbs[i] -= l;
|
||||
for (k=0; k<this.fullOffset.length; k++) {
|
||||
limbs[i+this.fullOffset[k]] -= this.fullFactor[k] * l;
|
||||
}
|
||||
this.normalize();
|
||||
}
|
||||
};
|
||||
|
||||
/** mostly constant-time, very expensive full reduction.
|
||||
* @this {sjcl.bn}
|
||||
*/
|
||||
ppr.fullReduce = function() {
|
||||
var greater, i;
|
||||
// massively above the modulus, may be negative
|
||||
|
||||
this._strongReduce();
|
||||
// less than twice the modulus, may be negative
|
||||
|
||||
this.addM(this.modulus);
|
||||
this.addM(this.modulus);
|
||||
this.normalize();
|
||||
// probably 2-3x the modulus
|
||||
|
||||
this._strongReduce();
|
||||
// less than the power of 2. still may be more than
|
||||
// the modulus
|
||||
|
||||
// HACK: pad out to this length
|
||||
for (i=this.limbs.length; i<this.modOffset; i++) {
|
||||
this.limbs[i] = 0;
|
||||
}
|
||||
|
||||
// constant-time subtract modulus
|
||||
greater = this.greaterEquals(this.modulus);
|
||||
for (i=0; i<this.limbs.length; i++) {
|
||||
this.limbs[i] -= this.modulus.limbs[i] * greater;
|
||||
}
|
||||
this.cnormalize();
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
/** @this {sjcl.bn} */
|
||||
ppr.inverse = function() {
|
||||
return (this.power(this.modulus.sub(2)));
|
||||
};
|
||||
|
||||
p.fromBits = sjcl.bn.fromBits;
|
||||
|
||||
return p;
|
||||
};
|
||||
|
||||
// a small Mersenne prime
|
||||
sjcl.bn.prime = {
|
||||
p127: sjcl.bn.pseudoMersennePrime(127, [[0,-1]]),
|
||||
|
||||
// Bernstein's prime for Curve25519
|
||||
p25519: sjcl.bn.pseudoMersennePrime(255, [[0,-19]]),
|
||||
|
||||
// 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]])
|
||||
};
|
||||
|
||||
sjcl.bn.random = function(modulus, paranoia) {
|
||||
if (typeof modulus !== "object") { modulus = new sjcl.bn(modulus); }
|
||||
var words, i, l = modulus.limbs.length, m = modulus.limbs[l-1]+1, out = new sjcl.bn();
|
||||
while (true) {
|
||||
// get a sequence whose first digits make sense
|
||||
do {
|
||||
words = sjcl.random.randomWords(l, paranoia);
|
||||
if (words[l-1] < 0) { words[l-1] += 0x100000000; }
|
||||
} while (Math.floor(words[l-1] / m) === Math.floor(0x100000000 / m));
|
||||
words[l-1] %= m;
|
||||
|
||||
// mask off all the limbs
|
||||
for (i=0; i<l-1; i++) {
|
||||
words[i] &= modulus.radixMask;
|
||||
}
|
||||
|
||||
// check the rest of the digitssj
|
||||
out.limbs = words;
|
||||
if (!out.greaterEquals(modulus)) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
/** @fileOverview CBC mode implementation
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @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() {
|
||||
sjcl.mode.cbc = {
|
||||
/** The name of the mode.
|
||||
* @constant
|
||||
*/
|
||||
name: "cbc",
|
||||
|
||||
/** Encrypt in CBC mode with PKCS#5 padding.
|
||||
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} plaintext The plaintext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data. Must be empty.
|
||||
* @return The encrypted data, an array of bytes.
|
||||
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified.
|
||||
*/
|
||||
encrypt: function(prp, plaintext, iv, adata) {
|
||||
if (adata && adata.length) {
|
||||
throw new sjcl.exception.invalid("cbc can't authenticate data");
|
||||
}
|
||||
if (sjcl.bitArray.bitLength(iv) !== 128) {
|
||||
throw new sjcl.exception.invalid("cbc iv must be 128 bits");
|
||||
}
|
||||
var i,
|
||||
w = sjcl.bitArray,
|
||||
xor = w._xor4,
|
||||
bl = w.bitLength(plaintext),
|
||||
bp = 0,
|
||||
output = [];
|
||||
|
||||
if (bl&7) {
|
||||
throw new sjcl.exception.invalid("pkcs#5 padding only works for multiples of a byte");
|
||||
}
|
||||
|
||||
for (i=0; bp+128 <= bl; i+=4, bp+=128) {
|
||||
/* Encrypt a non-final block */
|
||||
iv = prp.encrypt(xor(iv, plaintext.slice(i,i+4)));
|
||||
output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);
|
||||
}
|
||||
|
||||
/* Construct the pad. */
|
||||
bl = (16 - ((bl >> 3) & 15)) * 0x1010101;
|
||||
|
||||
/* Pad and encrypt. */
|
||||
iv = prp.encrypt(xor(iv,w.concat(plaintext,[bl,bl,bl,bl]).slice(i,i+4)));
|
||||
output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);
|
||||
return output;
|
||||
},
|
||||
|
||||
/** Decrypt in CBC mode.
|
||||
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} ciphertext The ciphertext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data. It must be empty.
|
||||
* @return The decrypted data, an array of bytes.
|
||||
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified.
|
||||
* @throws {sjcl.exception.corrupt} if if the message is corrupt.
|
||||
*/
|
||||
decrypt: function(prp, ciphertext, iv, adata) {
|
||||
if (adata && adata.length) {
|
||||
throw new sjcl.exception.invalid("cbc can't authenticate data");
|
||||
}
|
||||
if (sjcl.bitArray.bitLength(iv) !== 128) {
|
||||
throw new sjcl.exception.invalid("cbc iv must be 128 bits");
|
||||
}
|
||||
if ((sjcl.bitArray.bitLength(ciphertext) & 127) || !ciphertext.length) {
|
||||
throw new sjcl.exception.corrupt("cbc ciphertext must be a positive multiple of the block size");
|
||||
}
|
||||
var i,
|
||||
w = sjcl.bitArray,
|
||||
xor = w._xor4,
|
||||
bi, bo,
|
||||
output = [];
|
||||
|
||||
adata = adata || [];
|
||||
|
||||
for (i=0; i<ciphertext.length; i+=4) {
|
||||
bi = ciphertext.slice(i,i+4);
|
||||
bo = xor(iv,prp.decrypt(bi));
|
||||
output.splice(i,0,bo[0],bo[1],bo[2],bo[3]);
|
||||
iv = bi;
|
||||
}
|
||||
|
||||
/* check and remove the pad */
|
||||
bi = output[i-1] & 255;
|
||||
if (bi == 0 || bi > 16) {
|
||||
throw new sjcl.exception.corrupt("pkcs#5 padding corrupt");
|
||||
}
|
||||
bo = bi * 0x1010101;
|
||||
if (!w.equal(w.bitSlice([bo,bo,bo,bo], 0, bi*8),
|
||||
w.bitSlice(output, output.length*32 - bi*8, output.length*32))) {
|
||||
throw new sjcl.exception.corrupt("pkcs#5 padding corrupt");
|
||||
}
|
||||
|
||||
return w.bitSlice(output, 0, output.length*32 - bi*8);
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,185 +0,0 @@
|
||||
/** @fileOverview CCM mode implementation.
|
||||
*
|
||||
* Special thanks to Roy Nicholson for pointing out a bug in our
|
||||
* implementation.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace CTR mode with CBC MAC. */
|
||||
sjcl.mode.ccm = {
|
||||
/** The name of the mode.
|
||||
* @constant
|
||||
*/
|
||||
name: "ccm",
|
||||
|
||||
/** Encrypt in CCM mode.
|
||||
* @static
|
||||
* @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} plaintext The plaintext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data.
|
||||
* @param {Number} [tlen=64] the desired tag length, in bits.
|
||||
* @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;
|
||||
tlen = tlen || 64;
|
||||
adata = adata || [];
|
||||
|
||||
if (ivl < 7) {
|
||||
throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");
|
||||
}
|
||||
|
||||
// compute the length of the length
|
||||
for (L=2; L<4 && ol >>> 8*L; L++) {}
|
||||
if (L < 15 - ivl) { L = 15-ivl; }
|
||||
iv = w.clamp(iv,8*(15-L));
|
||||
|
||||
// compute the tag
|
||||
tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L);
|
||||
|
||||
// encrypt
|
||||
out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);
|
||||
|
||||
return w.concat(out.data, out.tag);
|
||||
},
|
||||
|
||||
/** Decrypt in CCM mode.
|
||||
* @static
|
||||
* @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} ciphertext The ciphertext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [[]] adata The authenticated data.
|
||||
* @param {Number} [64] tlen the desired tag length, in bits.
|
||||
* @return {bitArray} The decrypted data.
|
||||
*/
|
||||
decrypt: function(prf, ciphertext, iv, adata, tlen) {
|
||||
tlen = tlen || 64;
|
||||
adata = adata || [];
|
||||
var L, i,
|
||||
w=sjcl.bitArray,
|
||||
ivl = w.bitLength(iv) / 8,
|
||||
ol = w.bitLength(ciphertext),
|
||||
out = w.clamp(ciphertext, ol - tlen),
|
||||
tag = w.bitSlice(ciphertext, ol - tlen), tag2;
|
||||
|
||||
|
||||
ol = (ol - tlen) / 8;
|
||||
|
||||
if (ivl < 7) {
|
||||
throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");
|
||||
}
|
||||
|
||||
// compute the length of the length
|
||||
for (L=2; L<4 && ol >>> 8*L; L++) {}
|
||||
if (L < 15 - ivl) { L = 15-ivl; }
|
||||
iv = w.clamp(iv,8*(15-L));
|
||||
|
||||
// decrypt
|
||||
out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);
|
||||
|
||||
// check the tag
|
||||
tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L);
|
||||
if (!w.equal(out.tag, tag2)) {
|
||||
throw new sjcl.exception.corrupt("ccm: tag doesn't match");
|
||||
}
|
||||
|
||||
return out.data;
|
||||
},
|
||||
|
||||
/* Compute the (unencrypted) authentication tag, according to the CCM specification
|
||||
* @param {Object} prf The pseudorandom function.
|
||||
* @param {bitArray} plaintext The plaintext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} adata The authenticated data.
|
||||
* @param {Number} tlen the desired tag length, in bits.
|
||||
* @return {bitArray} The tag, but not yet encrypted.
|
||||
* @private
|
||||
*/
|
||||
_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;
|
||||
|
||||
tlen /= 8;
|
||||
|
||||
// check tag length and message length
|
||||
if (tlen % 2 || tlen < 4 || tlen > 16) {
|
||||
throw new sjcl.exception.invalid("ccm: invalid tag length");
|
||||
}
|
||||
|
||||
if (adata.length > 0xFFFFFFFF || plaintext.length > 0xFFFFFFFF) {
|
||||
// I don't want to deal with extracting high words from doubles.
|
||||
throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data");
|
||||
}
|
||||
|
||||
// mac the flags
|
||||
mac = [w.partial(8, (adata.length ? 1<<6 : 0) | (tlen-2) << 2 | L-1)];
|
||||
|
||||
// mac the iv and length
|
||||
mac = w.concat(mac, iv);
|
||||
mac[3] |= w.bitLength(plaintext)/8;
|
||||
mac = prf.encrypt(mac);
|
||||
|
||||
|
||||
if (adata.length) {
|
||||
// mac the associated data. start with its length...
|
||||
tmp = w.bitLength(adata)/8;
|
||||
if (tmp <= 0xFEFF) {
|
||||
macData = [w.partial(16, tmp)];
|
||||
} else if (tmp <= 0xFFFFFFFF) {
|
||||
macData = w.concat([w.partial(16,0xFFFE)], [tmp]);
|
||||
} // else ...
|
||||
|
||||
// mac the data itself
|
||||
macData = w.concat(macData, adata);
|
||||
for (i=0; i<macData.length; i += 4) {
|
||||
mac = prf.encrypt(xor(mac, macData.slice(i,i+4).concat([0,0,0])));
|
||||
}
|
||||
}
|
||||
|
||||
// mac the plaintext
|
||||
for (i=0; i<plaintext.length; i+=4) {
|
||||
mac = prf.encrypt(xor(mac, plaintext.slice(i,i+4).concat([0,0,0])));
|
||||
}
|
||||
|
||||
return w.clamp(mac, tlen * 8);
|
||||
},
|
||||
|
||||
/** CCM CTR mode.
|
||||
* Encrypt or decrypt data and tag with the prf in CCM-style CTR mode.
|
||||
* May mutate its arguments.
|
||||
* @param {Object} prf The PRF.
|
||||
* @param {bitArray} data The data to be encrypted or decrypted.
|
||||
* @param {bitArray} iv The initialization vector.
|
||||
* @param {bitArray} tag The authentication tag.
|
||||
* @param {Number} tlen The length of th etag, in bits.
|
||||
* @param {Number} L The CCM L value.
|
||||
* @return {Object} An object with data and tag, the en/decryption of data and tag values.
|
||||
* @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);
|
||||
|
||||
// start the ctr
|
||||
ctr = w.concat([w.partial(8,L-1)],iv).concat([0,0,0]).slice(0,4);
|
||||
|
||||
// en/decrypt the tag
|
||||
tag = w.bitSlice(xor(tag,prf.encrypt(ctr)), 0, tlen);
|
||||
|
||||
// en/decrypt the data
|
||||
if (!l) { return {tag:tag, data:[]}; }
|
||||
|
||||
for (i=0; i<l; i+=4) {
|
||||
ctr[3]++;
|
||||
enc = prf.encrypt(ctr);
|
||||
data[i] ^= enc[0];
|
||||
data[i+1] ^= enc[1];
|
||||
data[i+2] ^= enc[2];
|
||||
data[i+3] ^= enc[3];
|
||||
}
|
||||
return { tag:tag, data:w.clamp(data,bl) };
|
||||
}
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
/** @fileOverview Bit array codec implementations.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace Base64 encoding/decoding */
|
||||
sjcl.codec.base64 = {
|
||||
/** The base64 alphabet.
|
||||
* @private
|
||||
*/
|
||||
_chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
|
||||
|
||||
/** 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) + '-_';
|
||||
for (i=0; out.length * 6 < bl; ) {
|
||||
out += c.charAt((ta ^ arr[i]>>>bits) >>> 26);
|
||||
if (bits < 6) {
|
||||
ta = arr[i] << (6-bits);
|
||||
bits += 26;
|
||||
i++;
|
||||
} else {
|
||||
ta <<= 6;
|
||||
bits -= 6;
|
||||
}
|
||||
}
|
||||
while ((out.length & 3) && !_noEquals) { out += "="; }
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Convert from a base64 string to a bitArray */
|
||||
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) + '-_';
|
||||
for (i=0; i<str.length; i++) {
|
||||
x = c.indexOf(str.charAt(i));
|
||||
if (x < 0) {
|
||||
throw new sjcl.exception.invalid("this isn't base64!");
|
||||
}
|
||||
if (bits > 26) {
|
||||
bits -= 26;
|
||||
out.push(ta ^ x>>>bits);
|
||||
ta = x << (32-bits);
|
||||
} else {
|
||||
bits += 6;
|
||||
ta ^= x << (32-bits);
|
||||
}
|
||||
}
|
||||
if (bits&56) {
|
||||
out.push(sjcl.bitArray.partial(bits&56, ta, 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.codec.base64url = {
|
||||
fromBits: function (arr) { return sjcl.codec.base64.fromBits(arr,1,1); },
|
||||
toBits: function (str) { return sjcl.codec.base64.toBits(str,1); }
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
/** @fileOverview Bit array codec implementations.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace Arrays of bytes */
|
||||
sjcl.codec.bytes = {
|
||||
/** Convert from a bitArray to an array of bytes. */
|
||||
fromBits: function (arr) {
|
||||
var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;
|
||||
for (i=0; i<bl/8; i++) {
|
||||
if ((i&3) === 0) {
|
||||
tmp = arr[i/4];
|
||||
}
|
||||
out.push(tmp >>> 24);
|
||||
tmp <<= 8;
|
||||
}
|
||||
return out;
|
||||
},
|
||||
/** Convert from an array of bytes to a bitArray. */
|
||||
toBits: function (bytes) {
|
||||
var out = [], i, tmp=0;
|
||||
for (i=0; i<bytes.length; i++) {
|
||||
tmp = tmp << 8 | bytes[i];
|
||||
if ((i&3) === 3) {
|
||||
out.push(tmp);
|
||||
tmp = 0;
|
||||
}
|
||||
}
|
||||
if (i&3) {
|
||||
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
/** @fileOverview Bit array codec implementations.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace Hexadecimal */
|
||||
sjcl.codec.hex = {
|
||||
/** Convert from a bitArray to a hex string. */
|
||||
fromBits: function (arr) {
|
||||
var out = "", i, x;
|
||||
for (i=0; i<arr.length; i++) {
|
||||
out += ((arr[i]|0)+0xF00000000000).toString(16).substr(4);
|
||||
}
|
||||
return out.substr(0, sjcl.bitArray.bitLength(arr)/4);//.replace(/(.{8})/g, "$1 ");
|
||||
},
|
||||
/** Convert from a hex string to a bitArray. */
|
||||
toBits: function (str) {
|
||||
var i, out=[], len;
|
||||
str = str.replace(/\s|0x/g, "");
|
||||
len = str.length;
|
||||
str = str + "00000000";
|
||||
for (i=0; i<str.length; i+=8) {
|
||||
out.push(parseInt(str.substr(i,8),16)^0);
|
||||
}
|
||||
return sjcl.bitArray.clamp(out, len*4);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
/** @fileOverview Bit array codec implementations.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace UTF-8 strings */
|
||||
sjcl.codec.utf8String = {
|
||||
/** Convert from a bitArray to a UTF-8 string. */
|
||||
fromBits: function (arr) {
|
||||
var out = "", bl = sjcl.bitArray.bitLength(arr), i, tmp;
|
||||
for (i=0; i<bl/8; i++) {
|
||||
if ((i&3) === 0) {
|
||||
tmp = arr[i/4];
|
||||
}
|
||||
out += String.fromCharCode(tmp >>> 24);
|
||||
tmp <<= 8;
|
||||
}
|
||||
return decodeURIComponent(escape(out));
|
||||
},
|
||||
|
||||
/** Convert from a UTF-8 string to a bitArray. */
|
||||
toBits: function (str) {
|
||||
str = unescape(encodeURIComponent(str));
|
||||
var out = [], i, tmp=0;
|
||||
for (i=0; i<str.length; i++) {
|
||||
tmp = tmp << 8 | str.charCodeAt(i);
|
||||
if ((i&3) === 3) {
|
||||
out.push(tmp);
|
||||
tmp = 0;
|
||||
}
|
||||
}
|
||||
if (i&3) {
|
||||
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
@@ -1,285 +0,0 @@
|
||||
/** @fileOverview Convenince functions centered around JSON encapsulation.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace JSON encapsulation */
|
||||
sjcl.json = {
|
||||
/** Default values for encryption */
|
||||
defaults: { v:1, iter:1000, ks:128, ts:64, mode:"ccm", adata:"", cipher:"aes" },
|
||||
|
||||
/** 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.
|
||||
* @throws {sjcl.exception.invalid} if a parameter is invalid.
|
||||
*/
|
||||
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);
|
||||
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) ||
|
||||
(p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||
|
||||
(p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||
|
||||
(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);
|
||||
p.salt = tmp.salt;
|
||||
} else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.publicKey) {
|
||||
tmp = password.kem();
|
||||
p.kemtag = tmp.tag;
|
||||
password = tmp.key.slice(0,p.ks/32);
|
||||
}
|
||||
if (typeof plaintext === "string") {
|
||||
plaintext = sjcl.codec.utf8String.toBits(plaintext);
|
||||
}
|
||||
if (typeof adata === "string") {
|
||||
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 j.encode(p);
|
||||
},
|
||||
|
||||
/** 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) {
|
||||
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;
|
||||
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) ||
|
||||
(p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||
|
||||
(p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||
|
||||
(!p.iv) ||
|
||||
(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);
|
||||
p.salt = tmp.salt;
|
||||
} else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.secretKey) {
|
||||
password = password.unkem(sjcl.codec.base64.toBits(p.kemtag)).slice(0,p.ks/32);
|
||||
}
|
||||
if (typeof adata === "string") {
|
||||
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);
|
||||
},
|
||||
|
||||
/** Encode a flat structure into a JSON string.
|
||||
* @param {Object} obj The structure to encode.
|
||||
* @return {String} A JSON string.
|
||||
* @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property.
|
||||
* @throws {sjcl.exception.bug} if a parameter has an unsupported type.
|
||||
*/
|
||||
encode: function (obj) {
|
||||
var i, out='{', comma='';
|
||||
for (i in obj) {
|
||||
if (obj.hasOwnProperty(i)) {
|
||||
if (!i.match(/^[a-z0-9]+$/i)) {
|
||||
throw new sjcl.exception.invalid("json encode: invalid property name");
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
return out+'}';
|
||||
},
|
||||
|
||||
/** Decode a simple (flat) JSON string into a structure. The ciphertext,
|
||||
* adata, salt and iv will be base64-decoded.
|
||||
* @param {String} str The string.
|
||||
* @return {Object} The decoded structure.
|
||||
* @throws {sjcl.exception.invalid} if str isn't (simple) JSON.
|
||||
*/
|
||||
decode: function (str) {
|
||||
str = str.replace(/\s/g,'');
|
||||
if (!str.match(/^\{.*\}$/)) {
|
||||
throw new sjcl.exception.invalid("json decode: this isn't json!");
|
||||
}
|
||||
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))) {
|
||||
throw new sjcl.exception.invalid("json decode: this isn't json!");
|
||||
}
|
||||
if (m[3]) {
|
||||
out[m[2]] = parseInt(m[3],10);
|
||||
} else {
|
||||
out[m[2]] = m[2].match(/^(ct|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Insert all elements of src into target, modifying and returning target.
|
||||
* @param {Object} target The object to be modified.
|
||||
* @param {Object} src The object to pull data from.
|
||||
* @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.
|
||||
* @return {Object} target.
|
||||
* @private
|
||||
*/
|
||||
_add: function (target, src, requireSame) {
|
||||
if (target === undefined) { target = {}; }
|
||||
if (src === undefined) { return target; }
|
||||
var i;
|
||||
for (i in src) {
|
||||
if (src.hasOwnProperty(i)) {
|
||||
if (requireSame && target[i] !== undefined && target[i] !== src[i]) {
|
||||
throw new sjcl.exception.invalid("required parameter overridden");
|
||||
}
|
||||
target[i] = src[i];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
},
|
||||
|
||||
/** Remove all elements of minus from plus. Does not modify plus.
|
||||
* @private
|
||||
*/
|
||||
_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;
|
||||
},
|
||||
|
||||
/** Return only the specified elements of src.
|
||||
* @private
|
||||
*/
|
||||
_filter: function (src, filter) {
|
||||
var out = {}, i;
|
||||
for (i=0; i<filter.length; i++) {
|
||||
if (src[filter[i]] !== undefined) {
|
||||
out[filter[i]] = src[filter[i]];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
/** Simple encryption function; convenient shorthand for sjcl.json.encrypt.
|
||||
* @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.
|
||||
*/
|
||||
sjcl.encrypt = sjcl.json.encrypt;
|
||||
|
||||
/** Simple decryption function; convenient shorthand for sjcl.json.decrypt.
|
||||
* @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.
|
||||
*/
|
||||
sjcl.decrypt = sjcl.json.decrypt;
|
||||
|
||||
/** The cache for cachedPbkdf2.
|
||||
* @private
|
||||
*/
|
||||
sjcl.misc._pbkdf2Cache = {};
|
||||
|
||||
/** Cached PBKDF2 key derivation.
|
||||
* @param {String} password The password.
|
||||
* @param {Object} [params] 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) {
|
||||
var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;
|
||||
|
||||
obj = obj || {};
|
||||
iter = obj.iter || 1000;
|
||||
|
||||
/* open the cache for this password and iteration count */
|
||||
cp = cache[password] = cache[password] || {};
|
||||
c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?
|
||||
obj.salt.slice(0) : sjcl.random.randomWords(2,0) };
|
||||
|
||||
salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;
|
||||
|
||||
c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);
|
||||
return { key: c[salt].slice(0), salt:salt.slice(0) };
|
||||
};
|
||||
|
||||
|
||||
@@ -1,420 +0,0 @@
|
||||
sjcl.ecc = {};
|
||||
|
||||
/**
|
||||
* Represents a point on a curve in affine coordinates.
|
||||
* @constructor
|
||||
* @param {sjcl.ecc.curve} curve The curve that this point lies on.
|
||||
* @param {bigInt} x The x coordinate.
|
||||
* @param {bigInt} y The y coordinate.
|
||||
*/
|
||||
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;
|
||||
};
|
||||
|
||||
|
||||
|
||||
sjcl.ecc.point.prototype = {
|
||||
toJac: function() {
|
||||
return new sjcl.ecc.pointJac(this.curve, this.x, this.y, new this.curve.field(1));
|
||||
},
|
||||
|
||||
mult: function(k) {
|
||||
return this.toJac().mult(k, this).toAffine();
|
||||
},
|
||||
|
||||
/**
|
||||
* Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.
|
||||
* @param {bigInt} k The coefficient to multiply this by.
|
||||
* @param {bigInt} k2 The coefficient to multiply affine2 this by.
|
||||
* @param {sjcl.ecc.point} affine The other point in affine coordinates.
|
||||
* @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.
|
||||
*/
|
||||
mult2: function(k, k2, affine2) {
|
||||
return this.toJac().mult2(k, this, k2, affine2).toAffine();
|
||||
},
|
||||
|
||||
multiples: function() {
|
||||
var m, i, j;
|
||||
if (this._multiples === undefined) {
|
||||
j = this.toJac().doubl();
|
||||
m = this._multiples = [new sjcl.ecc.point(this.curve), this, j.toAffine()];
|
||||
for (i=3; i<16; i++) {
|
||||
j = j.add(this);
|
||||
m.push(j.toAffine());
|
||||
}
|
||||
}
|
||||
return this._multiples;
|
||||
},
|
||||
|
||||
isValid: function() {
|
||||
return this.y.square().equals(this.curve.b.add(this.x.mul(this.curve.a.add(this.x.square()))));
|
||||
},
|
||||
|
||||
toBits: function() {
|
||||
return sjcl.bitArray.concat(this.x.toBits(), this.y.toBits());
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents a point on a curve in Jacobian coordinates. Coordinates can be specified as bigInts or strings (which
|
||||
* will be converted to bigInts).
|
||||
*
|
||||
* @constructor
|
||||
* @param {bigInt/string} x The x coordinate.
|
||||
* @param {bigInt/string} y The y coordinate.
|
||||
* @param {bigInt/string} z The z coordinate.
|
||||
* @param {sjcl.ecc.curve} curve The curve that this point lies on.
|
||||
*/
|
||||
sjcl.ecc.pointJac = function(curve, x, y, z) {
|
||||
if (x === undefined) {
|
||||
this.isIdentity = true;
|
||||
} else {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.isIdentity = false;
|
||||
}
|
||||
this.curve = curve;
|
||||
};
|
||||
|
||||
sjcl.ecc.pointJac.prototype = {
|
||||
/**
|
||||
* Adds S and T and returns the result in Jacobian coordinates. Note that S must be in Jacobian coordinates and T must be in affine coordinates.
|
||||
* @param {sjcl.ecc.pointJac} S One of the points to add, in Jacobian coordinates.
|
||||
* @param {sjcl.ecc.point} T The other point to add, in affine coordinates.
|
||||
* @return {sjcl.ecc.pointJac} The sum of the two points, in Jacobian coordinates.
|
||||
*/
|
||||
add: function(T) {
|
||||
var S = this, sz2, c, d, c2, x1, x2, x, y1, y2, y, z;
|
||||
if (S.curve !== T.curve) {
|
||||
throw("sjcl.ecc.add(): Points must be on the same curve to add them!");
|
||||
}
|
||||
|
||||
if (S.isIdentity) {
|
||||
return T.toJac();
|
||||
} else if (T.isIdentity) {
|
||||
return S;
|
||||
}
|
||||
|
||||
sz2 = S.z.square();
|
||||
c = T.x.mul(sz2).subM(S.x);
|
||||
|
||||
if (c.equals(0)) {
|
||||
if (S.y.equals(T.y.mul(sz2.mul(S.z)))) {
|
||||
// same point
|
||||
return S.doubl();
|
||||
} else {
|
||||
// inverses
|
||||
return new sjcl.ecc.pointJac(S.curve);
|
||||
}
|
||||
}
|
||||
|
||||
d = T.y.mul(sz2.mul(S.z)).subM(S.y);
|
||||
c2 = c.square();
|
||||
|
||||
x1 = d.square();
|
||||
x2 = c.square().mul(c).addM( S.x.add(S.x).mul(c2) );
|
||||
x = x1.subM(x2);
|
||||
|
||||
y1 = S.x.mul(c2).subM(x).mul(d);
|
||||
y2 = S.y.mul(c.square().mul(c));
|
||||
y = y1.subM(y2);
|
||||
|
||||
z = S.z.mul(c);
|
||||
|
||||
return new sjcl.ecc.pointJac(this.curve,x,y,z);
|
||||
},
|
||||
|
||||
/**
|
||||
* doubles this point.
|
||||
* @return {sjcl.ecc.pointJac} The doubled point.
|
||||
*/
|
||||
doubl: function() {
|
||||
if (this.isIdentity) { return this; }
|
||||
|
||||
var
|
||||
y2 = this.y.square(),
|
||||
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)),
|
||||
x = c.square().subM(a).subM(a),
|
||||
y = a.sub(x).mul(c).subM(b),
|
||||
z = this.y.add(this.y).mul(this.z);
|
||||
return new sjcl.ecc.pointJac(this.curve, x, y, z);
|
||||
},
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
var zi = this.z.inverse(), zi2 = zi.square();
|
||||
return new sjcl.ecc.point(this.curve, this.x.mul(zi2).fullReduce(), this.y.mul(zi2.mul(zi)).fullReduce());
|
||||
},
|
||||
|
||||
/**
|
||||
* Multiply this point by k and return the answer in Jacobian coordinates.
|
||||
* @param {bigInt} k The coefficient to multiply by.
|
||||
* @param {sjcl.ecc.point} affine This point in affine coordinates.
|
||||
* @return {sjcl.ecc.pointJac} The result of the multiplication, in Jacobian coordinates.
|
||||
*/
|
||||
mult: function(k, affine) {
|
||||
if (typeof(k) === "number") {
|
||||
k = [k];
|
||||
} else if (k.limbs !== undefined) {
|
||||
k = k.normalize().limbs;
|
||||
}
|
||||
|
||||
var i, j, out = new sjcl.ecc.point(this.curve).toJac(), multiples = affine.multiples();
|
||||
|
||||
for (i=k.length-1; i>=0; i--) {
|
||||
for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) {
|
||||
out = out.doubl().doubl().doubl().doubl().add(multiples[k[i]>>j & 0xF]);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
/**
|
||||
* Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.
|
||||
* @param {bigInt} k The coefficient to multiply this by.
|
||||
* @param {sjcl.ecc.point} affine This point in affine coordinates.
|
||||
* @param {bigInt} k2 The coefficient to multiply affine2 this by.
|
||||
* @param {sjcl.ecc.point} affine The other point in affine coordinates.
|
||||
* @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.
|
||||
*/
|
||||
mult2: function(k1, affine, k2, affine2) {
|
||||
if (typeof(k1) === "number") {
|
||||
k1 = [k1];
|
||||
} else if (k1.limbs !== undefined) {
|
||||
k1 = k1.normalize().limbs;
|
||||
}
|
||||
|
||||
if (typeof(k2) === "number") {
|
||||
k2 = [k2];
|
||||
} else if (k2.limbs !== undefined) {
|
||||
k2 = k2.normalize().limbs;
|
||||
}
|
||||
|
||||
var i, j, out = new sjcl.ecc.point(this.curve).toJac(), m1 = affine.multiples(),
|
||||
m2 = affine2.multiples(), l1, l2;
|
||||
|
||||
for (i=Math.max(k1.length,k2.length)-1; i>=0; i--) {
|
||||
l1 = k1[i] | 0;
|
||||
l2 = k2[i] | 0;
|
||||
for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) {
|
||||
out = out.doubl().doubl().doubl().doubl().add(m1[l1>>j & 0xF]).add(m2[l2>>j & 0xF]);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
isValid: function() {
|
||||
var z2 = this.z.square(), z4 = z2.square(), z6 = z4.mul(z2);
|
||||
return this.y.square().equals(
|
||||
this.curve.b.mul(z6).add(this.x.mul(
|
||||
this.curve.a.mul(z4).add(this.x.square()))));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Construct an elliptic curve. Most users will not use this and instead start with one of the NIST curves defined below.
|
||||
*
|
||||
* @constructor
|
||||
* @param {bigInt} p The prime modulus.
|
||||
* @param {bigInt} r The prime order of the curve.
|
||||
* @param {bigInt} a The constant a in the equation of the curve y^2 = x^3 + ax + b (for NIST curves, a is always -3).
|
||||
* @param {bigInt} x The x coordinate of a base point of the curve.
|
||||
* @param {bigInt} y The y coordinate of a base point of the curve.
|
||||
*/
|
||||
sjcl.ecc.curve = function(Field, r, a, b, x, y) {
|
||||
this.field = Field;
|
||||
this.r = Field.prototype.modulus.sub(r);
|
||||
this.a = new Field(a);
|
||||
this.b = new Field(b);
|
||||
this.G = new sjcl.ecc.point(this, new Field(x), new Field(y));
|
||||
};
|
||||
|
||||
sjcl.ecc.curve.prototype.fromBits = function (bits) {
|
||||
var w = sjcl.bitArray, l = this.field.prototype.exponent + 7 & -8,
|
||||
p = new sjcl.ecc.point(this, this.field.fromBits(w.bitSlice(bits, 0, l)),
|
||||
this.field.fromBits(w.bitSlice(bits, l, 2*l)));
|
||||
if (!p.isValid()) {
|
||||
throw new sjcl.exception.corrupt("not on the curve!");
|
||||
}
|
||||
return p;
|
||||
};
|
||||
|
||||
sjcl.ecc.curves = {
|
||||
c192: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p192,
|
||||
"0x662107c8eb94364e4b2dd7ce",
|
||||
-3,
|
||||
"0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
|
||||
"0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
|
||||
"0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811"),
|
||||
|
||||
c224: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p224,
|
||||
"0xe95c1f470fc1ec22d6baa3a3d5c4",
|
||||
-3,
|
||||
"0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4",
|
||||
"0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21",
|
||||
"0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"),
|
||||
|
||||
c256: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p256,
|
||||
"0x4319055358e8617b0c46353d039cdaae",
|
||||
-3,
|
||||
"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
|
||||
"0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
|
||||
"0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),
|
||||
|
||||
c384: new sjcl.ecc.curve(
|
||||
sjcl.bn.prime.p384,
|
||||
"0x389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68c",
|
||||
-3,
|
||||
"0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef",
|
||||
"0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
|
||||
"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
|
||||
};
|
||||
|
||||
|
||||
/* 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) };
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
sjcl.ecc._dh("elGamal");
|
||||
|
||||
sjcl.ecc.elGamal.publicKey.prototype = {
|
||||
kem: function(paranoia) {
|
||||
var sec = sjcl.bn.random(this._curve.r, paranoia),
|
||||
tag = this._curve.G.mult(sec).toBits(),
|
||||
key = sjcl.hash.sha256.hash(this._point.mult(sec).toBits());
|
||||
return { key: key, tag: tag };
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.ecc.elGamal.secretKey.prototype = {
|
||||
unkem: function(tag) {
|
||||
return sjcl.hash.sha256.hash(this._curve.fromBits(tag).mult(this._exponent).toBits());
|
||||
},
|
||||
|
||||
dh: function(pk) {
|
||||
return sjcl.hash.sha256.hash(pk._point.mult(this._exponent).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));
|
||||
}
|
||||
};
|
||||
|
||||
sjcl.ecc.ecdsa.publicKey.prototype = {
|
||||
verify: function(hash, rs, fakeLegacyVersion) {
|
||||
if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {
|
||||
hash = sjcl.bitArray.clamp(hash, this._curveBitLength);
|
||||
}
|
||||
var w = sjcl.bitArray,
|
||||
R = this._curve.r,
|
||||
l = this._curveBitLength,
|
||||
r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
|
||||
ss = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),
|
||||
s = fakeLegacyVersion ? ss : ss.inverseMod(R),
|
||||
hG = sjcl.bn.fromBits(hash).mul(s).mod(R),
|
||||
hA = r.mul(s).mod(R),
|
||||
r2 = this._curve.G.mult2(hG, hA, this._point).x;
|
||||
if (r.equals(0) || ss.equals(0) || r.greaterEquals(R) || ss.greaterEquals(R) || !r2.equals(r)) {
|
||||
if (fakeLegacyVersion === undefined) {
|
||||
return this.verify(hash, rs, true);
|
||||
} else {
|
||||
throw (new sjcl.exception.corrupt("signature didn't check out"));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -1,183 +0,0 @@
|
||||
/** @fileOverview GCM mode implementation.
|
||||
*
|
||||
* @author Juho Vähä-Herttua
|
||||
*/
|
||||
|
||||
/** @namespace Galois/Counter mode. */
|
||||
sjcl.mode.gcm = {
|
||||
/** The name of the mode.
|
||||
* @constant
|
||||
*/
|
||||
name: "gcm",
|
||||
|
||||
/** Encrypt in GCM mode.
|
||||
* @static
|
||||
* @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} plaintext The plaintext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data.
|
||||
* @param {Number} [tlen=128] The desired tag length, in bits.
|
||||
* @return {bitArray} The encrypted data, an array of bytes.
|
||||
*/
|
||||
encrypt: function (prf, plaintext, iv, adata, tlen) {
|
||||
var out, data = plaintext.slice(0), w=sjcl.bitArray;
|
||||
tlen = tlen || 128;
|
||||
adata = adata || [];
|
||||
|
||||
// encrypt and tag
|
||||
out = sjcl.mode.gcm._ctrMode(true, prf, data, adata, iv, tlen);
|
||||
|
||||
return w.concat(out.data, out.tag);
|
||||
},
|
||||
|
||||
/** Decrypt in GCM mode.
|
||||
* @static
|
||||
* @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} ciphertext The ciphertext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data.
|
||||
* @param {Number} [tlen=128] The desired tag length, in bits.
|
||||
* @return {bitArray} The decrypted data.
|
||||
*/
|
||||
decrypt: function (prf, ciphertext, iv, adata, tlen) {
|
||||
var out, data = ciphertext.slice(0), tag, w=sjcl.bitArray, l=w.bitLength(data);
|
||||
tlen = tlen || 128;
|
||||
adata = adata || [];
|
||||
|
||||
// Slice tag out of data
|
||||
if (tlen <= l) {
|
||||
tag = w.bitSlice(data, l-tlen);
|
||||
data = w.bitSlice(data, 0, l-tlen);
|
||||
} else {
|
||||
tag = data;
|
||||
data = [];
|
||||
}
|
||||
|
||||
// decrypt and tag
|
||||
out = sjcl.mode.gcm._ctrMode(false, prf, data, adata, iv, tlen);
|
||||
|
||||
if (!w.equal(out.tag, tag)) {
|
||||
throw new sjcl.exception.corrupt("gcm: tag doesn't match");
|
||||
}
|
||||
return out.data;
|
||||
},
|
||||
|
||||
/* Compute the galois multiplication of X and Y
|
||||
* @private
|
||||
*/
|
||||
_galoisMultiply: function (x, y) {
|
||||
var i, j, xi, Zi, Vi, lsb_Vi, w=sjcl.bitArray, xor=w._xor4;
|
||||
|
||||
Zi = [0,0,0,0];
|
||||
Vi = y.slice(0);
|
||||
|
||||
// Block size is 128 bits, run 128 times to get Z_128
|
||||
for (i=0; i<128; i++) {
|
||||
xi = (x[Math.floor(i/32)] & (1 << (31-i%32))) !== 0;
|
||||
if (xi) {
|
||||
// Z_i+1 = Z_i ^ V_i
|
||||
Zi = xor(Zi, Vi);
|
||||
}
|
||||
|
||||
// Store the value of LSB(V_i)
|
||||
lsb_Vi = (Vi[3] & 1) !== 0;
|
||||
|
||||
// V_i+1 = V_i >> 1
|
||||
for (j=3; j>0; j--) {
|
||||
Vi[j] = (Vi[j] >>> 1) | ((Vi[j-1]&1) << 31);
|
||||
}
|
||||
Vi[0] = Vi[0] >>> 1;
|
||||
|
||||
// If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
|
||||
if (lsb_Vi) {
|
||||
Vi[0] = Vi[0] ^ (0xe1 << 24);
|
||||
}
|
||||
}
|
||||
return Zi;
|
||||
},
|
||||
|
||||
_ghash: function(H, Y0, data) {
|
||||
var Yi, i, l = data.length;
|
||||
|
||||
Yi = Y0.slice(0);
|
||||
for (i=0; i<l; i+=4) {
|
||||
Yi[0] ^= 0xffffffff&data[i];
|
||||
Yi[1] ^= 0xffffffff&data[i+1];
|
||||
Yi[2] ^= 0xffffffff&data[i+2];
|
||||
Yi[3] ^= 0xffffffff&data[i+3];
|
||||
Yi = sjcl.mode.gcm._galoisMultiply(Yi, H);
|
||||
}
|
||||
return Yi;
|
||||
},
|
||||
|
||||
/** GCM CTR mode.
|
||||
* Encrypt or decrypt data and tag with the prf in GCM-style CTR mode.
|
||||
* @param {Boolean} encrypt True if encrypt, false if decrypt.
|
||||
* @param {Object} prf The PRF.
|
||||
* @param {bitArray} data The data to be encrypted or decrypted.
|
||||
* @param {bitArray} iv The initialization vector.
|
||||
* @param {bitArray} adata The associated data to be tagged.
|
||||
* @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;
|
||||
|
||||
// Calculate data lengths
|
||||
l = data.length;
|
||||
bl = w.bitLength(data);
|
||||
abl = w.bitLength(adata);
|
||||
ivbl = w.bitLength(iv);
|
||||
|
||||
// Calculate the parameters
|
||||
H = prf.encrypt([0,0,0,0]);
|
||||
if (ivbl === 96) {
|
||||
J0 = iv.slice(0);
|
||||
J0 = w.concat(J0, [1]);
|
||||
} else {
|
||||
J0 = sjcl.mode.gcm._ghash(H, [0,0,0,0], iv);
|
||||
J0 = sjcl.mode.gcm._ghash(H, J0, [0,0,Math.floor(ivbl/0x100000000),ivbl&0xffffffff]);
|
||||
}
|
||||
S0 = sjcl.mode.gcm._ghash(H, [0,0,0,0], adata);
|
||||
|
||||
// Initialize ctr and tag
|
||||
ctr = J0.slice(0);
|
||||
tag = S0.slice(0);
|
||||
|
||||
// If decrypting, calculate hash
|
||||
if (!encrypt) {
|
||||
tag = sjcl.mode.gcm._ghash(H, S0, data);
|
||||
}
|
||||
|
||||
// Encrypt all the data
|
||||
for (i=0; i<l; i+=4) {
|
||||
ctr[3]++;
|
||||
enc = prf.encrypt(ctr);
|
||||
data[i] ^= enc[0];
|
||||
data[i+1] ^= enc[1];
|
||||
data[i+2] ^= enc[2];
|
||||
data[i+3] ^= enc[3];
|
||||
}
|
||||
data = w.clamp(data, bl);
|
||||
|
||||
// If encrypting, calculate hash
|
||||
if (encrypt) {
|
||||
tag = sjcl.mode.gcm._ghash(H, S0, data);
|
||||
}
|
||||
|
||||
// Calculate last block from bit lengths, ugly because bitwise operations are 32-bit
|
||||
last = [
|
||||
Math.floor(abl/0x100000000), abl&0xffffffff,
|
||||
Math.floor(bl/0x100000000), bl&0xffffffff
|
||||
];
|
||||
|
||||
// Calculate the final tag block
|
||||
tag = sjcl.mode.gcm._ghash(H, tag, last);
|
||||
enc = prf.encrypt(J0);
|
||||
tag[0] ^= enc[0];
|
||||
tag[1] ^= enc[1];
|
||||
tag[2] ^= enc[2];
|
||||
tag[3] ^= enc[3];
|
||||
|
||||
return { tag:w.bitSlice(tag, 0, tlen), data:data };
|
||||
}
|
||||
};
|
||||
@@ -1,39 +0,0 @@
|
||||
/** @fileOverview HMAC implementation.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** HMAC with the specified hash function.
|
||||
* @constructor
|
||||
* @param {bitArray} key the key for HMAC.
|
||||
* @param {Object} [hash=sjcl.hash.sha256] The hash function to use.
|
||||
*/
|
||||
sjcl.misc.hmac = function (key, Hash) {
|
||||
this._hash = Hash = Hash || sjcl.hash.sha256;
|
||||
var exKey = [[],[]], i,
|
||||
bs = Hash.prototype.blockSize / 32;
|
||||
this._baseHash = [new Hash(), new Hash()];
|
||||
|
||||
if (key.length > bs) {
|
||||
key = Hash.hash(key);
|
||||
}
|
||||
|
||||
for (i=0; i<bs; i++) {
|
||||
exKey[0][i] = key[i]^0x36363636;
|
||||
exKey[1][i] = key[i]^0x5C5C5C5C;
|
||||
}
|
||||
|
||||
this._baseHash[0].update(exKey[0]);
|
||||
this._baseHash[1].update(exKey[1]);
|
||||
};
|
||||
|
||||
/** 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();
|
||||
};
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
/** @fileOverview OCB 2.0 implementation
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @namespace
|
||||
* Phil Rogaway's Offset CodeBook mode, version 2.0.
|
||||
* May be covered by US and international patents.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
sjcl.mode.ocb2 = {
|
||||
/** The name of the mode.
|
||||
* @constant
|
||||
*/
|
||||
name: "ocb2",
|
||||
|
||||
/** Encrypt in OCB mode, version 2.0.
|
||||
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} plaintext The plaintext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data.
|
||||
* @param {Number} [tlen=64] the desired tag length, in bits.
|
||||
* @param [false] premac 1 if the authentication data is pre-macced with PMAC.
|
||||
* @return The encrypted data, an array of bytes.
|
||||
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits.
|
||||
*/
|
||||
encrypt: function(prp, plaintext, iv, adata, tlen, premac) {
|
||||
if (sjcl.bitArray.bitLength(iv) !== 128) {
|
||||
throw new sjcl.exception.invalid("ocb iv must be 128 bits");
|
||||
}
|
||||
var i,
|
||||
times2 = sjcl.mode.ocb2._times2,
|
||||
w = sjcl.bitArray,
|
||||
xor = w._xor4,
|
||||
checksum = [0,0,0,0],
|
||||
delta = times2(prp.encrypt(iv)),
|
||||
bi, bl,
|
||||
output = [],
|
||||
pad;
|
||||
|
||||
adata = adata || [];
|
||||
tlen = tlen || 64;
|
||||
|
||||
for (i=0; i+4 < plaintext.length; i+=4) {
|
||||
/* Encrypt a non-final block */
|
||||
bi = plaintext.slice(i,i+4);
|
||||
checksum = xor(checksum, bi);
|
||||
output = output.concat(xor(delta,prp.encrypt(xor(delta, bi))));
|
||||
delta = times2(delta);
|
||||
}
|
||||
|
||||
/* Chop out the final block */
|
||||
bi = plaintext.slice(i);
|
||||
bl = w.bitLength(bi);
|
||||
pad = prp.encrypt(xor(delta,[0,0,0,bl]));
|
||||
bi = w.clamp(xor(bi.concat([0,0,0]),pad), bl);
|
||||
|
||||
/* Checksum the final block, and finalize the checksum */
|
||||
checksum = xor(checksum,xor(bi.concat([0,0,0]),pad));
|
||||
checksum = prp.encrypt(xor(checksum,xor(delta,times2(delta))));
|
||||
|
||||
/* MAC the header */
|
||||
if (adata.length) {
|
||||
checksum = xor(checksum, premac ? adata : sjcl.mode.ocb2.pmac(prp, adata));
|
||||
}
|
||||
|
||||
return output.concat(w.concat(bi, w.clamp(checksum, tlen)));
|
||||
},
|
||||
|
||||
/** Decrypt in OCB mode.
|
||||
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} ciphertext The ciphertext data.
|
||||
* @param {bitArray} iv The initialization value.
|
||||
* @param {bitArray} [adata=[]] The authenticated data.
|
||||
* @param {Number} [tlen=64] the desired tag length, in bits.
|
||||
* @param {boolean} [premac=false] true if the authentication data is pre-macced with PMAC.
|
||||
* @return The decrypted data, an array of bytes.
|
||||
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits.
|
||||
* @throws {sjcl.exception.corrupt} if if the message is corrupt.
|
||||
*/
|
||||
decrypt: function(prp, ciphertext, iv, adata, tlen, premac) {
|
||||
if (sjcl.bitArray.bitLength(iv) !== 128) {
|
||||
throw new sjcl.exception.invalid("ocb iv must be 128 bits");
|
||||
}
|
||||
tlen = tlen || 64;
|
||||
var i,
|
||||
times2 = sjcl.mode.ocb2._times2,
|
||||
w = sjcl.bitArray,
|
||||
xor = w._xor4,
|
||||
checksum = [0,0,0,0],
|
||||
delta = times2(prp.encrypt(iv)),
|
||||
bi, bl,
|
||||
len = sjcl.bitArray.bitLength(ciphertext) - tlen,
|
||||
output = [],
|
||||
pad;
|
||||
|
||||
adata = adata || [];
|
||||
|
||||
for (i=0; i+4 < len/32; i+=4) {
|
||||
/* Decrypt a non-final block */
|
||||
bi = xor(delta, prp.decrypt(xor(delta, ciphertext.slice(i,i+4))));
|
||||
checksum = xor(checksum, bi);
|
||||
output = output.concat(bi);
|
||||
delta = times2(delta);
|
||||
}
|
||||
|
||||
/* Chop out and decrypt the final block */
|
||||
bl = len-i*32;
|
||||
pad = prp.encrypt(xor(delta,[0,0,0,bl]));
|
||||
bi = xor(pad, w.clamp(ciphertext.slice(i),bl).concat([0,0,0]));
|
||||
|
||||
/* Checksum the final block, and finalize the checksum */
|
||||
checksum = xor(checksum, bi);
|
||||
checksum = prp.encrypt(xor(checksum, xor(delta, times2(delta))));
|
||||
|
||||
/* MAC the header */
|
||||
if (adata.length) {
|
||||
checksum = xor(checksum, premac ? adata : sjcl.mode.ocb2.pmac(prp, adata));
|
||||
}
|
||||
|
||||
if (!w.equal(w.clamp(checksum, tlen), w.bitSlice(ciphertext, len))) {
|
||||
throw new sjcl.exception.corrupt("ocb: tag doesn't match");
|
||||
}
|
||||
|
||||
return output.concat(w.clamp(bi,bl));
|
||||
},
|
||||
|
||||
/** PMAC authentication for OCB associated data.
|
||||
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
|
||||
* @param {bitArray} adata The authenticated data.
|
||||
*/
|
||||
pmac: function(prp, adata) {
|
||||
var i,
|
||||
times2 = sjcl.mode.ocb2._times2,
|
||||
w = sjcl.bitArray,
|
||||
xor = w._xor4,
|
||||
checksum = [0,0,0,0],
|
||||
delta = prp.encrypt([0,0,0,0]),
|
||||
bi;
|
||||
|
||||
delta = xor(delta,times2(times2(delta)));
|
||||
|
||||
for (i=0; i+4<adata.length; i+=4) {
|
||||
delta = times2(delta);
|
||||
checksum = xor(checksum, prp.encrypt(xor(delta, adata.slice(i,i+4))));
|
||||
}
|
||||
|
||||
bi = adata.slice(i);
|
||||
if (w.bitLength(bi) < 128) {
|
||||
delta = xor(delta,times2(delta));
|
||||
bi = w.concat(bi,[0x80000000|0,0,0,0]);
|
||||
}
|
||||
checksum = xor(checksum, bi);
|
||||
return prp.encrypt(xor(times2(xor(delta,times2(delta))), checksum));
|
||||
},
|
||||
|
||||
/** Double a block of words, OCB style.
|
||||
* @private
|
||||
*/
|
||||
_times2: function(x) {
|
||||
return [x[0]<<1 ^ x[1]>>>31,
|
||||
x[1]<<1 ^ x[2]>>>31,
|
||||
x[2]<<1 ^ x[3]>>>31,
|
||||
x[3]<<1 ^ (x[0]>>>31)*0x87];
|
||||
}
|
||||
};
|
||||
@@ -1,54 +0,0 @@
|
||||
/** @fileOverview Password-based key-derivation function, version 2.0.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** Password-Based Key-Derivation Function, version 2.0.
|
||||
*
|
||||
* Generate keys from passwords using PBKDF2-HMAC-SHA256.
|
||||
*
|
||||
* 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 {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.
|
||||
* @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family.
|
||||
* @return {bitArray} the derived key.
|
||||
*/
|
||||
sjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {
|
||||
count = count || 1000;
|
||||
|
||||
if (length < 0 || count < 0) {
|
||||
throw sjcl.exception.invalid("invalid params to pbkdf2");
|
||||
}
|
||||
|
||||
if (typeof password === "string") {
|
||||
password = sjcl.codec.utf8String.toBits(password);
|
||||
}
|
||||
|
||||
Prff = Prff || sjcl.misc.hmac;
|
||||
|
||||
var prf = new Prff(password),
|
||||
u, ui, i, j, k, out = [], b = sjcl.bitArray;
|
||||
|
||||
for (k = 1; 32 * out.length < (length || 1); k++) {
|
||||
u = ui = prf.encrypt(b.concat(salt,[k]));
|
||||
|
||||
for (i=1; i<count; i++) {
|
||||
ui = prf.encrypt(ui);
|
||||
for (j=0; j<ui.length; j++) {
|
||||
u[j] ^= ui[j];
|
||||
}
|
||||
}
|
||||
|
||||
out = out.concat(u);
|
||||
}
|
||||
|
||||
if (length) { out = b.clamp(out, length); }
|
||||
|
||||
return out;
|
||||
};
|
||||
@@ -1,406 +0,0 @@
|
||||
/** @fileOverview Random number generator.
|
||||
*
|
||||
* @author Emily Stark
|
||||
* @author Mike Hamburg
|
||||
* @author Dan Boneh
|
||||
*/
|
||||
|
||||
/** @constructor
|
||||
* @class Random number generator
|
||||
*
|
||||
* @description
|
||||
* <p>
|
||||
* This random number generator is a derivative of Ferguson and Schneier's
|
||||
* generator Fortuna. It collects entropy from various events into several
|
||||
* pools, implemented by streaming SHA-256 instances. It differs from
|
||||
* ordinary Fortuna in a few ways, though.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Most importantly, it has an entropy estimator. This is present because
|
||||
* there is a strong conflict here between making the generator available
|
||||
* as soon as possible, and making sure that it doesn't "run on empty".
|
||||
* In Fortuna, there is a saved state file, and the system is likely to have
|
||||
* time to warm up.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Second, because users are unlikely to stay on the page for very long,
|
||||
* and to speed startup time, the number of pools increases logarithmically:
|
||||
* a new pool is created when the previous one is actually used for a reseed.
|
||||
* This gives the same asymptotic guarantees as Fortuna, but gives more
|
||||
* entropy to early reseeds.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The entire mechanism here feels pretty klunky. Furthermore, there are
|
||||
* several improvements that should be made, including support for
|
||||
* dedicated cryptographic functions that may be present in some browsers;
|
||||
* state files in local storage; cookies containing randomness; etc. So
|
||||
* look for improvements in future versions.
|
||||
* </p>
|
||||
*/
|
||||
sjcl.prng = function(defaultParanoia) {
|
||||
|
||||
/* private */
|
||||
this._pools = [new sjcl.hash.sha256()];
|
||||
this._poolEntropy = [0];
|
||||
this._reseedCount = 0;
|
||||
this._robins = {};
|
||||
this._eventId = 0;
|
||||
|
||||
this._collectorIds = {};
|
||||
this._collectorIdNext = 0;
|
||||
|
||||
this._strength = 0;
|
||||
this._poolStrength = 0;
|
||||
this._nextReseed = 0;
|
||||
this._key = [0,0,0,0,0,0,0,0];
|
||||
this._counter = [0,0,0,0];
|
||||
this._cipher = undefined;
|
||||
this._defaultParanoia = defaultParanoia;
|
||||
|
||||
/* event listener stuff */
|
||||
this._collectorsStarted = false;
|
||||
this._callbacks = {progress: {}, seeded: {}};
|
||||
this._callbackI = 0;
|
||||
|
||||
/* constants */
|
||||
this._NOT_READY = 0;
|
||||
this._READY = 1;
|
||||
this._REQUIRES_RESEED = 2;
|
||||
|
||||
this._MAX_WORDS_PER_BURST = 65536;
|
||||
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
|
||||
* @param {Number} nwords The number of words to generate.
|
||||
*/
|
||||
randomWords: function (nwords, paranoia) {
|
||||
var out = [], i, readiness = this.isReady(paranoia), g;
|
||||
|
||||
if (readiness === this._NOT_READY) {
|
||||
throw new sjcl.exception.notReady("generator isn't seeded");
|
||||
} else if (readiness & this._REQUIRES_RESEED) {
|
||||
this._reseedFromPools(!(readiness & this._READY));
|
||||
}
|
||||
|
||||
for (i=0; i<nwords; i+= 4) {
|
||||
if ((i+1) % this._MAX_WORDS_PER_BURST === 0) {
|
||||
this._gate();
|
||||
}
|
||||
|
||||
g = this._gen4words();
|
||||
out.push(g[0],g[1],g[2],g[3]);
|
||||
}
|
||||
this._gate();
|
||||
|
||||
return out.slice(0,nwords);
|
||||
},
|
||||
|
||||
setDefaultParanoia: function (paranoia) {
|
||||
this._defaultParanoia = paranoia;
|
||||
},
|
||||
|
||||
/**
|
||||
* Add entropy to the pools.
|
||||
* @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string
|
||||
* @param {Number} estimatedEntropy The estimated entropy of data, in bits
|
||||
* @param {String} source The source of the entropy, eg "mouse"
|
||||
*/
|
||||
addEntropy: function (data, estimatedEntropy, source) {
|
||||
source = source || "user";
|
||||
|
||||
var id,
|
||||
i, tmp,
|
||||
t = (new Date()).valueOf(),
|
||||
robin = this._robins[source],
|
||||
oldReady = this.isReady(), err = 0;
|
||||
|
||||
id = this._collectorIds[source];
|
||||
if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }
|
||||
|
||||
if (robin === undefined) { robin = this._robins[source] = 0; }
|
||||
this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length;
|
||||
|
||||
switch(typeof(data)) {
|
||||
|
||||
case "number":
|
||||
if (estimatedEntropy === undefined) {
|
||||
estimatedEntropy = 1;
|
||||
}
|
||||
this._pools[robin].update([id,this._eventId++,1,estimatedEntropy,t,1,data|0]);
|
||||
break;
|
||||
|
||||
case "object":
|
||||
var objName = Object.prototype.toString.call(data);
|
||||
if (objName === "[object Uint32Array]") {
|
||||
tmp = [];
|
||||
for (i = 0; i < data.length; i++) {
|
||||
tmp.push(data[i]);
|
||||
}
|
||||
data = tmp;
|
||||
} else {
|
||||
if (objName !== "[object Array]") {
|
||||
err = 1;
|
||||
}
|
||||
for (i=0; i<data.length && !err; i++) {
|
||||
if (typeof(data[i]) != "number") {
|
||||
err = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!err) {
|
||||
if (estimatedEntropy === undefined) {
|
||||
/* horrible entropy estimator */
|
||||
estimatedEntropy = 0;
|
||||
for (i=0; i<data.length; i++) {
|
||||
tmp= data[i];
|
||||
while (tmp>0) {
|
||||
estimatedEntropy++;
|
||||
tmp = tmp >>> 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._pools[robin].update([id,this._eventId++,2,estimatedEntropy,t,data.length].concat(data));
|
||||
}
|
||||
break;
|
||||
|
||||
case "string":
|
||||
if (estimatedEntropy === undefined) {
|
||||
/* English text has just over 1 bit per character of entropy.
|
||||
* But this might be HTML or something, and have far less
|
||||
* entropy than English... Oh well, let's just say one bit.
|
||||
*/
|
||||
estimatedEntropy = data.length;
|
||||
}
|
||||
this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]);
|
||||
this._pools[robin].update(data);
|
||||
break;
|
||||
|
||||
default:
|
||||
err=1;
|
||||
}
|
||||
if (err) {
|
||||
throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");
|
||||
}
|
||||
|
||||
/* record the new strength */
|
||||
this._poolEntropy[robin] += estimatedEntropy;
|
||||
this._poolStrength += estimatedEntropy;
|
||||
|
||||
/* fire off events */
|
||||
if (oldReady === this._NOT_READY) {
|
||||
if (this.isReady() !== this._NOT_READY) {
|
||||
this._fireEvent("seeded", Math.max(this._strength, this._poolStrength));
|
||||
}
|
||||
this._fireEvent("progress", this.getProgress());
|
||||
}
|
||||
},
|
||||
|
||||
/** Is the generator ready? */
|
||||
isReady: function (paranoia) {
|
||||
var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];
|
||||
|
||||
if (this._strength && this._strength >= entropyRequired) {
|
||||
return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?
|
||||
this._REQUIRES_RESEED | this._READY :
|
||||
this._READY;
|
||||
} else {
|
||||
return (this._poolStrength >= entropyRequired) ?
|
||||
this._REQUIRES_RESEED | this._NOT_READY :
|
||||
this._NOT_READY;
|
||||
}
|
||||
},
|
||||
|
||||
/** Get the generator's progress toward readiness, as a fraction */
|
||||
getProgress: function (paranoia) {
|
||||
var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];
|
||||
|
||||
if (this._strength >= entropyRequired) {
|
||||
return 1.0;
|
||||
} else {
|
||||
return (this._poolStrength > entropyRequired) ?
|
||||
1.0 :
|
||||
this._poolStrength / entropyRequired;
|
||||
}
|
||||
},
|
||||
|
||||
/** start the built-in entropy collectors */
|
||||
startCollectors: function () {
|
||||
if (this._collectorsStarted) { return; }
|
||||
|
||||
if (window.addEventListener) {
|
||||
window.addEventListener("load", this._loadTimeCollector, false);
|
||||
window.addEventListener("mousemove", this._mouseCollector, false);
|
||||
} else if (document.attachEvent) {
|
||||
document.attachEvent("onload", this._loadTimeCollector);
|
||||
document.attachEvent("onmousemove", this._mouseCollector);
|
||||
}
|
||||
else {
|
||||
throw new sjcl.exception.bug("can't attach event");
|
||||
}
|
||||
|
||||
this._collectorsStarted = true;
|
||||
},
|
||||
|
||||
/** stop the built-in entropy collectors */
|
||||
stopCollectors: function () {
|
||||
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);
|
||||
}
|
||||
this._collectorsStarted = false;
|
||||
},
|
||||
|
||||
/* use a cookie to store entropy.
|
||||
useCookie: function (all_cookies) {
|
||||
throw new sjcl.exception.bug("random: useCookie is unimplemented");
|
||||
},*/
|
||||
|
||||
/** add an event listener for progress or seeded-ness. */
|
||||
addEventListener: function (name, callback) {
|
||||
this._callbacks[name][this._callbackI++] = callback;
|
||||
},
|
||||
|
||||
/** 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) {
|
||||
jsTemp.push(j);
|
||||
}
|
||||
}
|
||||
|
||||
for (i=0; i<jsTemp.length; i++) {
|
||||
j = jsTemp[i];
|
||||
delete cbs[j];
|
||||
}
|
||||
},
|
||||
|
||||
/** Generate 4 random words, no reseed, no gate.
|
||||
* @private
|
||||
*/
|
||||
_gen4words: function () {
|
||||
for (var i=0; i<4; i++) {
|
||||
this._counter[i] = this._counter[i]+1 | 0;
|
||||
if (this._counter[i]) { break; }
|
||||
}
|
||||
return this._cipher.encrypt(this._counter);
|
||||
},
|
||||
|
||||
/* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.
|
||||
* @private
|
||||
*/
|
||||
_gate: function () {
|
||||
this._key = this._gen4words().concat(this._gen4words());
|
||||
this._cipher = new sjcl.cipher.aes(this._key);
|
||||
},
|
||||
|
||||
/** Reseed the generator with the given words
|
||||
* @private
|
||||
*/
|
||||
_reseed: function (seedWords) {
|
||||
this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
|
||||
this._cipher = new sjcl.cipher.aes(this._key);
|
||||
for (var i=0; i<4; i++) {
|
||||
this._counter[i] = this._counter[i]+1 | 0;
|
||||
if (this._counter[i]) { break; }
|
||||
}
|
||||
},
|
||||
|
||||
/** reseed the data from the entropy pools
|
||||
* @param full If set, use all the entropy pools in the reseed.
|
||||
*/
|
||||
_reseedFromPools: function (full) {
|
||||
var reseedData = [], strength = 0, i;
|
||||
|
||||
this._nextReseed = reseedData[0] =
|
||||
(new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
|
||||
|
||||
for (i=0; i<16; i++) {
|
||||
/* On some browsers, this is cryptographically random. So we might
|
||||
* as well toss it in the pot and stir...
|
||||
*/
|
||||
reseedData.push(Math.random()*0x100000000|0);
|
||||
}
|
||||
|
||||
for (i=0; i<this._pools.length; i++) {
|
||||
reseedData = reseedData.concat(this._pools[i].finalize());
|
||||
strength += this._poolEntropy[i];
|
||||
this._poolEntropy[i] = 0;
|
||||
|
||||
if (!full && (this._reseedCount & (1<<i))) { break; }
|
||||
}
|
||||
|
||||
/* if we used the last pool, push a new one onto the stack */
|
||||
if (this._reseedCount >= 1 << this._pools.length) {
|
||||
this._pools.push(new sjcl.hash.sha256());
|
||||
this._poolEntropy.push(0);
|
||||
}
|
||||
|
||||
/* how strong was this reseed? */
|
||||
this._poolStrength -= strength;
|
||||
if (strength > this._strength) {
|
||||
this._strength = strength;
|
||||
}
|
||||
|
||||
this._reseedCount ++;
|
||||
this._reseed(reseedData);
|
||||
},
|
||||
|
||||
_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");
|
||||
},
|
||||
|
||||
_loadTimeCollector: function (ev) {
|
||||
sjcl.random.addEntropy((new Date()).valueOf(), 2, "loadtime");
|
||||
},
|
||||
|
||||
_fireEvent: function (name, arg) {
|
||||
var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];
|
||||
/* 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)) {
|
||||
cbsTemp.push(cbs[j]);
|
||||
}
|
||||
}
|
||||
|
||||
for (j=0; j<cbsTemp.length; j++) {
|
||||
cbsTemp[j](arg);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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 :-(
|
||||
}
|
||||
})();
|
||||
@@ -1,165 +0,0 @@
|
||||
/** @fileOverview Javascript SHA-1 implementation.
|
||||
*
|
||||
* Based on the implementation in RFC 3174, method 1, and on the SJCL
|
||||
* SHA-256 implementation.
|
||||
*
|
||||
* @author Quinn Slack
|
||||
*/
|
||||
|
||||
/**
|
||||
* Context for a SHA-1 operation in progress.
|
||||
* @constructor
|
||||
* @class Secure Hash Algorithm, 160 bits.
|
||||
*/
|
||||
sjcl.hash.sha1 = function (hash) {
|
||||
if (hash) {
|
||||
this._h = hash._h.slice(0);
|
||||
this._buffer = hash._buffer.slice(0);
|
||||
this._length = hash._length;
|
||||
} else {
|
||||
this.reset();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Hash a string or an array of words.
|
||||
* @static
|
||||
* @param {bitArray|String} data the data to hash.
|
||||
* @return {bitArray} The hash value, an array of 5 big-endian words.
|
||||
*/
|
||||
sjcl.hash.sha1.hash = function (data) {
|
||||
return (new sjcl.hash.sha1()).update(data).finalize();
|
||||
};
|
||||
|
||||
sjcl.hash.sha1.prototype = {
|
||||
/**
|
||||
* The hash's block size, in bits.
|
||||
* @constant
|
||||
*/
|
||||
blockSize: 512,
|
||||
|
||||
/**
|
||||
* Reset the hash state.
|
||||
* @return this
|
||||
*/
|
||||
reset:function () {
|
||||
this._h = this._init.slice(0);
|
||||
this._buffer = [];
|
||||
this._length = 0;
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Input several words to the hash.
|
||||
* @param {bitArray|String} data the data to hash.
|
||||
* @return this
|
||||
*/
|
||||
update: function (data) {
|
||||
if (typeof data === "string") {
|
||||
data = sjcl.codec.utf8String.toBits(data);
|
||||
}
|
||||
var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),
|
||||
ol = this._length,
|
||||
nl = this._length = ol + sjcl.bitArray.bitLength(data);
|
||||
for (i = this.blockSize+ol & -this.blockSize; i <= nl;
|
||||
i+= this.blockSize) {
|
||||
this._block(b.splice(0,16));
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Complete hashing and output the hash value.
|
||||
* @return {bitArray} The hash value, an array of 5 big-endian words. TODO
|
||||
*/
|
||||
finalize:function () {
|
||||
var i, b = this._buffer, h = this._h;
|
||||
|
||||
// Round out and push the buffer
|
||||
b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]);
|
||||
// Round out the buffer to a multiple of 16 words, less the 2 length words.
|
||||
for (i = b.length + 2; i & 15; i++) {
|
||||
b.push(0);
|
||||
}
|
||||
|
||||
// append the length
|
||||
b.push(Math.floor(this._length / 0x100000000));
|
||||
b.push(this._length | 0);
|
||||
|
||||
while (b.length) {
|
||||
this._block(b.splice(0,16));
|
||||
}
|
||||
|
||||
this.reset();
|
||||
return h;
|
||||
},
|
||||
|
||||
/**
|
||||
* The SHA-1 initialization vector.
|
||||
* @private
|
||||
*/
|
||||
_init:[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],
|
||||
|
||||
/**
|
||||
* The SHA-1 hash key.
|
||||
* @private
|
||||
*/
|
||||
_key:[0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6],
|
||||
|
||||
/**
|
||||
* The SHA-1 logical functions f(0), f(1), ..., f(79).
|
||||
* @private
|
||||
*/
|
||||
_f:function(t, b, c, d) {
|
||||
if (t <= 19) {
|
||||
return (b & c) | (~b & d);
|
||||
} else if (t <= 39) {
|
||||
return b ^ c ^ d;
|
||||
} else if (t <= 59) {
|
||||
return (b & c) | (b & d) | (c & d);
|
||||
} else if (t <= 79) {
|
||||
return b ^ c ^ d;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Circular left-shift operator.
|
||||
* @private
|
||||
*/
|
||||
_S:function(n, x) {
|
||||
return (x << n) | (x >>> 32-n);
|
||||
},
|
||||
|
||||
/**
|
||||
* Perform one cycle of SHA-1.
|
||||
* @param {bitArray} words one block of words.
|
||||
* @private
|
||||
*/
|
||||
_block:function (words) {
|
||||
var t, tmp, a, b, c, d, e,
|
||||
w = words.slice(0),
|
||||
h = this._h,
|
||||
k = this._key;
|
||||
|
||||
a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4];
|
||||
|
||||
for (t=0; t<=79; t++) {
|
||||
if (t >= 16) {
|
||||
w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]);
|
||||
}
|
||||
tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] +
|
||||
this._key[Math.floor(t/20)]) | 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = this._S(30, b);
|
||||
b = a;
|
||||
a = tmp;
|
||||
}
|
||||
|
||||
h[0] = (h[0]+a) |0;
|
||||
h[1] = (h[1]+b) |0;
|
||||
h[2] = (h[2]+c) |0;
|
||||
h[3] = (h[3]+d) |0;
|
||||
h[4] = (h[4]+e) |0;
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user