@steemit/steem-js 0.8.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +202 -105
  2. package/dist/api/index.d.ts +128 -0
  3. package/dist/api/methods.d.ts +9 -0
  4. package/dist/api/rpc-auth.d.ts +43 -0
  5. package/dist/api/transports/base.d.ts +13 -0
  6. package/dist/api/transports/http.d.ts +9 -0
  7. package/dist/api/transports/index.d.ts +9 -0
  8. package/dist/api/transports/types.d.ts +35 -0
  9. package/dist/api/transports/ws.d.ts +18 -0
  10. package/dist/auth/ecc/index.d.ts +9 -0
  11. package/dist/auth/ecc/src/address.d.ts +13 -0
  12. package/dist/auth/ecc/src/aes.d.ts +16 -0
  13. package/dist/auth/ecc/src/brain_key.d.ts +1 -0
  14. package/dist/auth/ecc/src/ecdsa.d.ts +28 -0
  15. package/dist/auth/ecc/src/ecsignature.d.ts +19 -0
  16. package/dist/auth/ecc/src/enforce_types.d.ts +5 -0
  17. package/dist/auth/ecc/src/hash.d.ts +25 -0
  18. package/dist/auth/ecc/src/index.d.ts +9 -0
  19. package/dist/auth/ecc/src/key_private.d.ts +38 -0
  20. package/dist/auth/ecc/src/key_public.d.ts +41 -0
  21. package/dist/auth/ecc/src/key_utils.d.ts +9 -0
  22. package/dist/auth/ecc/src/signature.d.ts +18 -0
  23. package/dist/auth/ecc.d.ts +3 -0
  24. package/dist/auth/index.d.ts +48 -0
  25. package/dist/auth/key_classes.d.ts +3 -0
  26. package/dist/auth/serializer/transaction.d.ts +5 -0
  27. package/dist/auth/serializer.d.ts +19 -0
  28. package/dist/broadcast/helpers.d.ts +11 -0
  29. package/dist/broadcast/index.d.ts +43 -0
  30. package/dist/broadcast/operations.d.ts +6 -0
  31. package/dist/config.d.ts +27 -0
  32. package/dist/crypto/index.d.ts +25 -0
  33. package/dist/formatter/index.d.ts +92 -0
  34. package/dist/index.cjs +26436 -0
  35. package/dist/index.cjs.map +1 -0
  36. package/dist/index.d.ts +30 -0
  37. package/dist/index.js +26400 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/index.umd.js +58121 -0
  40. package/dist/index.umd.js.map +1 -0
  41. package/dist/memo/index.d.ts +11 -0
  42. package/dist/operations/index.d.ts +44 -0
  43. package/dist/serializer/convert.d.ts +12 -0
  44. package/dist/serializer/index.d.ts +11 -0
  45. package/dist/serializer/number_utils.d.ts +8 -0
  46. package/dist/serializer/precision.d.ts +5 -0
  47. package/dist/serializer/types.d.ts +36 -0
  48. package/dist/types/index.d.ts +131 -0
  49. package/dist/types.d.ts +34 -0
  50. package/dist/utils/debug.d.ts +36 -0
  51. package/dist/utils/index.d.ts +9 -0
  52. package/dist/utils.d.ts +2 -0
  53. package/package.json +68 -87
  54. package/.dockerignore +0 -12
  55. package/.editorconfig +0 -20
  56. package/.eslintrc +0 -27
  57. package/LICENSE +0 -21
  58. package/circle.yml +0 -3
  59. package/config.json +0 -10
  60. package/dist/steem-tests.min.js +0 -4097
  61. package/dist/steem.min.js +0 -2089
  62. package/docker-webpack.config.js +0 -44
  63. package/lib/api/index.js +0 -315
  64. package/lib/api/methods.js +0 -428
  65. package/lib/api/rpc-auth.js +0 -135
  66. package/lib/api/transports/base.js +0 -31
  67. package/lib/api/transports/http.js +0 -157
  68. package/lib/api/transports/index.js +0 -13
  69. package/lib/api/transports/ws.js +0 -128
  70. package/lib/auth/ecc/index.js +0 -13
  71. package/lib/auth/ecc/src/address.js +0 -54
  72. package/lib/auth/ecc/src/aes.js +0 -148
  73. package/lib/auth/ecc/src/brain_key.js +0 -13
  74. package/lib/auth/ecc/src/ecdsa.js +0 -193
  75. package/lib/auth/ecc/src/ecsignature.js +0 -102
  76. package/lib/auth/ecc/src/enforce_types.js +0 -42
  77. package/lib/auth/ecc/src/hash.js +0 -58
  78. package/lib/auth/ecc/src/key_private.js +0 -159
  79. package/lib/auth/ecc/src/key_public.js +0 -143
  80. package/lib/auth/ecc/src/key_utils.js +0 -70
  81. package/lib/auth/ecc/src/signature.js +0 -135
  82. package/lib/auth/index.js +0 -113
  83. package/lib/auth/memo.js +0 -119
  84. package/lib/auth/serializer/index.js +0 -15
  85. package/lib/auth/serializer/src/ChainTypes.js +0 -87
  86. package/lib/auth/serializer/src/convert.js +0 -34
  87. package/lib/auth/serializer/src/error_with_cause.js +0 -27
  88. package/lib/auth/serializer/src/fast_parser.js +0 -57
  89. package/lib/auth/serializer/src/number_utils.js +0 -43
  90. package/lib/auth/serializer/src/object_id.js +0 -43
  91. package/lib/auth/serializer/src/operations.js +0 -695
  92. package/lib/auth/serializer/src/precision.js +0 -77
  93. package/lib/auth/serializer/src/serializer.js +0 -165
  94. package/lib/auth/serializer/src/template.js +0 -22
  95. package/lib/auth/serializer/src/types.js +0 -1085
  96. package/lib/auth/serializer/src/validation.js +0 -300
  97. package/lib/broadcast/helpers.js +0 -140
  98. package/lib/broadcast/index.js +0 -106
  99. package/lib/broadcast/operations.js +0 -255
  100. package/lib/browser.js +0 -25
  101. package/lib/config.js +0 -23
  102. package/lib/formatter.js +0 -163
  103. package/lib/index.js +0 -21
  104. package/lib/utils.js +0 -50
  105. package/node-18.dockerfile +0 -28
  106. package/test/Crypto.js +0 -100
  107. package/test/KeyFormats.js +0 -105
  108. package/test/all_types.js +0 -115
  109. package/test/api.test.js +0 -363
  110. package/test/broadcast.test.js +0 -231
  111. package/test/browser/BrowserTests.js +0 -55
  112. package/test/comment.test.js +0 -83
  113. package/test/hf20-accounts.test.js +0 -76
  114. package/test/hf21-sps.test.js +0 -78
  115. package/test/memo.test.js +0 -37
  116. package/test/number_utils.js +0 -28
  117. package/test/operations_test.js +0 -39
  118. package/test/promise-broadcast.test.js +0 -86
  119. package/test/reputation.test.js +0 -68
  120. package/test/smt.test.js +0 -347
  121. package/test/test-post.json +0 -13
  122. package/test/test.html +0 -13
  123. package/test/test_helper.js +0 -19
  124. package/test/types_test.js +0 -139
  125. package/test-github-workflow.bat +0 -19
  126. package/test-github-workflow.sh +0 -15
  127. package/webpack/makeConfig.js +0 -113
  128. package/webpack.config.js +0 -2
@@ -1,157 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- exports.jsonRpc = jsonRpc;
8
- var _crossFetch = _interopRequireDefault(require("cross-fetch"));
9
- var _debug = _interopRequireDefault(require("debug"));
10
- var _retry = _interopRequireDefault(require("retry"));
11
- var _base = _interopRequireDefault(require("./base"));
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- const debug = (0, _debug.default)('steem:http');
14
- class RPCError extends Error {
15
- constructor(rpcError) {
16
- super(rpcError.message);
17
- this.name = 'RPCError';
18
- this.code = rpcError.code;
19
- this.data = rpcError.data;
20
- }
21
- }
22
-
23
- /**
24
- * Makes a JSON-RPC request using `fetch` or a user-provided `fetchMethod`.
25
- *
26
- * @param {string} uri - The URI to the JSON-RPC endpoint.
27
- * @param {string} options.method - The remote JSON-RPC method to call.
28
- * @param {string} options.id - ID for the request, for matching to a response.
29
- * @param {*} options.params - The params for the remote method.
30
- * @param {function} [options.fetchMethod=fetch] - A function with the same
31
- * signature as `fetch`, which can be used to make the network request, or for
32
- * stubbing in tests.
33
- * @param {number} [options.timeoutMs=30000] - Request timeout in milliseconds.
34
- */
35
- function jsonRpc(uri, {
36
- method,
37
- id,
38
- params,
39
- fetchMethod = _crossFetch.default,
40
- timeoutMs = 30000
41
- }) {
42
- const payload = {
43
- id,
44
- jsonrpc: '2.0',
45
- method,
46
- params
47
- };
48
- let timeoutId = null;
49
-
50
- // Create a promise that will reject after the timeout
51
- const timeoutPromise = new Promise((_, reject) => {
52
- timeoutId = setTimeout(() => {
53
- reject(new Error(`Request timeout after ${timeoutMs}ms`));
54
- }, timeoutMs);
55
- });
56
-
57
- // Create the fetch promise
58
- const fetchPromise = fetchMethod(uri, {
59
- body: JSON.stringify(payload),
60
- method: 'post',
61
- mode: 'cors',
62
- headers: {
63
- Accept: 'application/json, text/plain, */*',
64
- 'Content-Type': 'application/json'
65
- }
66
- }).then(res => {
67
- if (!res.ok) {
68
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
69
- }
70
- return res.json();
71
- }).then(rpcRes => {
72
- if (rpcRes.id !== id) {
73
- throw new Error(`Invalid response id: ${rpcRes.id}`);
74
- }
75
- if (rpcRes.error) {
76
- throw new RPCError(rpcRes.error);
77
- }
78
- return rpcRes.result;
79
- });
80
-
81
- // Race the fetch against the timeout
82
- return Promise.race([fetchPromise, timeoutPromise]).finally(() => {
83
- // Clear the timeout to avoid memory leaks
84
- if (timeoutId) {
85
- clearTimeout(timeoutId);
86
- }
87
- });
88
- }
89
- class HttpTransport extends _base.default {
90
- send(api, data, callback) {
91
- if (this.options.useAppbaseApi) {
92
- api = 'condenser_api';
93
- }
94
- debug('Steem::send', api, data);
95
- const id = data.id || this.id++;
96
- const params = [api, data.method, data.params];
97
- const retriable = this.retriable(api, data);
98
- const fetchMethod = this.options.fetchMethod;
99
-
100
- // Use a longer timeout for broadcast operations (60s) and standard operations (30s)
101
- const timeoutMs = this.isBroadcastOperation(data.method) ? 60000 : 30000;
102
- if (retriable) {
103
- retriable.attempt(currentAttempt => {
104
- jsonRpc(this.options.uri, {
105
- method: 'call',
106
- id,
107
- params,
108
- fetchMethod,
109
- timeoutMs
110
- }).then(res => {
111
- callback(null, res);
112
- }, err => {
113
- if (retriable.retry(err)) {
114
- return;
115
- }
116
- callback(retriable.mainError());
117
- });
118
- });
119
- } else {
120
- jsonRpc(this.options.uri, {
121
- method: 'call',
122
- id,
123
- params,
124
- fetchMethod,
125
- timeoutMs
126
- }).then(res => {
127
- callback(null, res);
128
- }, err => {
129
- callback(err);
130
- });
131
- }
132
- }
133
- isBroadcastOperation(method) {
134
- return this.nonRetriableOperations.some(op => op === method);
135
- }
136
- get nonRetriableOperations() {
137
- return this.options.nonRetriableOperations || ['broadcast_transaction', 'broadcast_transaction_with_callback', 'broadcast_transaction_synchronous', 'broadcast_block'];
138
- }
139
-
140
- // An object which can be used to track retries.
141
- retriable(api, data) {
142
- if (this.isBroadcastOperation(data.method)) {
143
- // Do not retry if the operation is non-retriable.
144
- return null;
145
- } else if (Object(this.options.retry) === this.options.retry) {
146
- // If `this.options.retry` is a map of options, pass those to operation.
147
- return _retry.default.operation(this.options.retry);
148
- } else if (this.options.retry) {
149
- // If `this.options.retry` is `true`, use default options.
150
- return _retry.default.operation();
151
- } else {
152
- // Otherwise, don't retry.
153
- return null;
154
- }
155
- }
156
- }
157
- exports.default = HttpTransport;
@@ -1,13 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _http = _interopRequireDefault(require("./http"));
8
- var _ws = _interopRequireDefault(require("./ws"));
9
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
10
- var _default = exports.default = {
11
- http: _http.default,
12
- ws: _ws.default
13
- };
@@ -1,128 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _bluebird = _interopRequireDefault(require("bluebird"));
8
- var _detectNode = _interopRequireDefault(require("detect-node"));
9
- var _debug = _interopRequireDefault(require("debug"));
10
- var _base = _interopRequireDefault(require("./base"));
11
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
- let WebSocket;
13
- if (_detectNode.default) {
14
- WebSocket = require('ws'); // eslint-disable-line global-require
15
- } else if (typeof window !== 'undefined') {
16
- WebSocket = window.WebSocket;
17
- } else {
18
- throw new Error("Couldn't decide on a `WebSocket` class");
19
- }
20
- const debug = (0, _debug.default)('steem:ws');
21
- class WsTransport extends _base.default {
22
- constructor(options = {}) {
23
- super(Object.assign({
24
- id: 0
25
- }, options));
26
- this._requests = new Map();
27
- this.inFlight = 0;
28
- this.isOpen = false;
29
- }
30
- start() {
31
- if (this.startPromise) {
32
- return this.startPromise;
33
- }
34
- this.startPromise = new _bluebird.default((resolve, reject) => {
35
- this.ws = new WebSocket(this.options.websocket);
36
- this.ws.onerror = err => {
37
- this.startPromise = null;
38
- reject(err);
39
- };
40
- this.ws.onopen = () => {
41
- this.isOpen = true;
42
- this.ws.onerror = this.onError.bind(this);
43
- this.ws.onmessage = this.onMessage.bind(this);
44
- this.ws.onclose = this.onClose.bind(this);
45
- resolve();
46
- };
47
- });
48
- return this.startPromise;
49
- }
50
- stop() {
51
- debug('Stopping...');
52
- this.startPromise = null;
53
- this.isOpen = false;
54
- this._requests.clear();
55
- if (this.ws) {
56
- this.ws.onerror = this.ws.onmessage = this.ws.onclose = null;
57
- this.ws.close();
58
- this.ws = null;
59
- }
60
- }
61
- send(api, data, callback) {
62
- debug('Steem::send', api, data);
63
- return this.start().then(() => {
64
- const deferral = {};
65
- new _bluebird.default((resolve, reject) => {
66
- deferral.resolve = val => {
67
- resolve(val);
68
- callback(null, val);
69
- };
70
- deferral.reject = val => {
71
- reject(val);
72
- callback(val);
73
- };
74
- });
75
- if (this.options.useAppbaseApi) {
76
- api = 'condenser_api';
77
- }
78
- const _request = {
79
- deferral,
80
- startedAt: Date.now(),
81
- message: {
82
- id: data.id || this.id++,
83
- method: 'call',
84
- jsonrpc: '2.0',
85
- params: [api, data.method, data.params]
86
- }
87
- };
88
- this.inFlight++;
89
- this._requests.set(_request.message.id, _request);
90
- this.ws.send(JSON.stringify(_request.message));
91
- return deferral;
92
- });
93
- }
94
- onError(error) {
95
- for (let _request of this._requests) {
96
- _request.deferral.reject(error);
97
- }
98
- this.stop();
99
- }
100
- onClose() {
101
- const error = new Error('Connection was closed');
102
- for (let _request of this._requests) {
103
- _request.deferral.reject(error);
104
- }
105
- this._requests.clear();
106
- }
107
- onMessage(websocketMessage) {
108
- const message = JSON.parse(websocketMessage.data);
109
- debug('-- Steem.onMessage -->', message.id);
110
- if (!this._requests.has(message.id)) {
111
- throw new Error(`Panic: no request in queue for message id ${message.id}`);
112
- }
113
- const _request = this._requests.get(message.id);
114
- this._requests.delete(message.id);
115
- const errorCause = message.error;
116
- if (errorCause) {
117
- const err = new Error(
118
- // eslint-disable-next-line prefer-template
119
- (errorCause.message || 'Failed to complete operation') + ' (see err.payload for the full error payload)');
120
- err.payload = message;
121
- _request.deferral.reject(err);
122
- } else {
123
- this.emit('track-performance', _request.message.method, Date.now() - _request.startedAt);
124
- _request.deferral.resolve(message.result);
125
- }
126
- }
127
- }
128
- exports.default = WsTransport;
@@ -1,13 +0,0 @@
1
- "use strict";
2
-
3
- module.exports = {
4
- Address: require("./src/address"),
5
- Aes: require("./src/aes"),
6
- PrivateKey: require("./src/key_private"),
7
- PublicKey: require("./src/key_public"),
8
- Signature: require("./src/signature"),
9
- brainKey: require("./src/brain_key"),
10
- key_utils: require("./src/key_utils"),
11
- hash: require("./src/hash"),
12
- ecc_config: require("../../config")
13
- };
@@ -1,54 +0,0 @@
1
- "use strict";
2
-
3
- const assert = require('assert');
4
- const config = require('../../../config');
5
- const hash = require('./hash');
6
- const base58 = require('bs58');
7
-
8
- /** Addresses are shortened non-reversable hashes of a public key. The full PublicKey is preferred.
9
- @deprecated
10
- */
11
- class Address {
12
- constructor(addy) {
13
- this.addy = addy;
14
- }
15
- static fromBuffer(buffer) {
16
- const _hash = hash.sha512(buffer);
17
- const addy = hash.ripemd160(_hash);
18
- return new Address(addy);
19
- }
20
- static fromString(string, address_prefix = config.get('address_prefix')) {
21
- const prefix = string.slice(0, address_prefix.length);
22
- assert.equal(address_prefix, prefix, `Expecting key to begin with ${address_prefix}, instead got ${prefix}`);
23
- let addy = string.slice(address_prefix.length);
24
- addy = new Buffer.from(base58.decode(addy), 'binary');
25
- const checksum = addy.slice(-4);
26
- addy = addy.slice(0, -4);
27
- let new_checksum = hash.ripemd160(addy);
28
- new_checksum = new_checksum.slice(0, 4);
29
- assert.deepEqual(checksum, new_checksum, 'Checksum did not match');
30
- return new Address(addy);
31
- }
32
-
33
- /** @return Address - Compressed PTS format (by default) */
34
- static fromPublic(public_key, compressed = true, version = 56) {
35
- const sha2 = hash.sha256(public_key.toBuffer(compressed));
36
- const rep = hash.ripemd160(sha2);
37
- const versionBuffer = new Buffer.alloc(1);
38
- versionBuffer.writeUInt8(0xFF & version, 0);
39
- const addr = Buffer.concat([versionBuffer, rep]);
40
- let check = hash.sha256(addr);
41
- check = hash.sha256(check);
42
- const buffer = Buffer.concat([addr, check.slice(0, 4)]);
43
- return new Address(hash.ripemd160(buffer));
44
- }
45
- toBuffer() {
46
- return this.addy;
47
- }
48
- toString(address_prefix = config.get('address_prefix')) {
49
- const checksum = hash.ripemd160(this.addy);
50
- const addy = Buffer.concat([this.addy, checksum.slice(0, 4)]);
51
- return address_prefix + base58.encode(addy);
52
- }
53
- }
54
- module.exports = Address;
@@ -1,148 +0,0 @@
1
- "use strict";
2
-
3
- const secureRandom = require('secure-random');
4
- const ByteBuffer = require('bytebuffer');
5
- const crypto = require('browserify-aes');
6
- const assert = require('assert');
7
- const PublicKey = require('./key_public');
8
- const PrivateKey = require('./key_private');
9
- const hash = require('./hash');
10
- const Long = ByteBuffer.Long;
11
-
12
- /**
13
- Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
14
- @throws {Error|TypeError} - "Invalid Key, ..."
15
- @arg {PrivateKey} private_key - required and used for decryption
16
- @arg {PublicKey} public_key - required and used to calculate the shared secret
17
- @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64
18
-
19
- @return {object}
20
- @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
21
- @property {Buffer} message - Plain text message
22
- @property {number} checksum - shared secret checksum
23
- */
24
- function encrypt(private_key, public_key, message, nonce = uniqueNonce()) {
25
- return crypt(private_key, public_key, nonce, message);
26
- }
27
-
28
- /**
29
- Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
30
- @arg {PrivateKey} private_key - required and used for decryption
31
- @arg {PublicKey} public_key - required and used to calculate the shared secret
32
- @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
33
- @arg {Buffer} message - Encrypted or plain text message
34
- @arg {number} checksum - shared secret checksum
35
- @throws {Error|TypeError} - "Invalid Key, ..."
36
- @return {Buffer} - message
37
- */
38
- function decrypt(private_key, public_key, nonce, message, checksum) {
39
- return crypt(private_key, public_key, nonce, message, checksum).message;
40
- }
41
-
42
- /**
43
- @arg {Buffer} message - Encrypted or plain text message (see checksum)
44
- @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt)
45
- */
46
- function crypt(private_key, public_key, nonce, message, checksum) {
47
- private_key = toPrivateObj(private_key);
48
- if (!private_key) throw new TypeError('private_key is required');
49
- public_key = toPublicObj(public_key);
50
- if (!public_key) throw new TypeError('public_key is required');
51
- nonce = toLongObj(nonce);
52
- if (!nonce) throw new TypeError('nonce is required');
53
- if (!Buffer.isBuffer(message)) {
54
- if (typeof message !== 'string') throw new TypeError('message should be buffer or string');
55
- message = new Buffer.from(message, 'binary');
56
- }
57
- if (checksum && typeof checksum !== 'number') throw new TypeError('checksum should be a number');
58
- const S = private_key.get_shared_secret(public_key);
59
- let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
60
- ebuf.writeUint64(nonce);
61
- ebuf.append(S.toString('binary'), 'binary');
62
- ebuf = new Buffer.from(ebuf.copy(0, ebuf.offset).toBinary(), 'binary');
63
- const encryption_key = hash.sha512(ebuf);
64
-
65
- // D E B U G
66
- // console.log('crypt', {
67
- // priv_to_pub: private_key.toPublicKey().toString(),
68
- // pub: public_key.toString(),
69
- // nonce: nonce.toString(),
70
- // message: message.length,
71
- // checksum,
72
- // S: S.toString('hex'),
73
- // encryption_key: encryption_key.toString('hex'),
74
- // })
75
-
76
- const iv = encryption_key.slice(32, 48);
77
- const key = encryption_key.slice(0, 32);
78
-
79
- // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.
80
- let check = hash.sha256(encryption_key);
81
- check = check.slice(0, 4);
82
- const cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
83
- check = cbuf.readUint32();
84
- if (checksum) {
85
- if (check !== checksum) throw new Error('Invalid key');
86
- message = cryptoJsDecrypt(message, key, iv);
87
- } else {
88
- message = cryptoJsEncrypt(message, key, iv);
89
- }
90
- return {
91
- nonce,
92
- message,
93
- checksum: check
94
- };
95
- }
96
-
97
- /** This method does not use a checksum, the returned data must be validated some other way.
98
- @arg {string|Buffer} ciphertext - binary format
99
- @return {Buffer}
100
- */
101
- function cryptoJsDecrypt(message, key, iv) {
102
- assert(message, "Missing cipher text");
103
- message = toBinaryBuffer(message);
104
- const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
105
- // decipher.setAutoPadding(true)
106
- message = Buffer.concat([decipher.update(message), decipher.final()]);
107
- return message;
108
- }
109
-
110
- /** This method does not use a checksum, the returned data must be validated some other way.
111
- @arg {string|Buffer} plaintext - binary format
112
- @return {Buffer} binary
113
- */
114
- function cryptoJsEncrypt(message, key, iv) {
115
- assert(message, "Missing plain text");
116
- message = toBinaryBuffer(message);
117
- const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
118
- // cipher.setAutoPadding(true)
119
- message = Buffer.concat([cipher.update(message), cipher.final()]);
120
- return message;
121
- }
122
-
123
- /** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time.
124
- */
125
- function uniqueNonce() {
126
- if (unique_nonce_entropy === null) {
127
- const b = secureRandom.randomUint8Array(2);
128
- unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10);
129
- }
130
- let long = Long.fromNumber(Date.now());
131
- const entropy = ++unique_nonce_entropy % 0xFFFF;
132
- // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
133
- // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0))
134
- long = long.shiftLeft(16).or(Long.fromNumber(entropy));
135
- // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
136
- return long.toString();
137
- }
138
- let unique_nonce_entropy = null;
139
- // for(let i=1; i < 10; i++) key.uniqueNonce()
140
-
141
- const toPrivateObj = o => o ? o.d ? o : PrivateKey.fromWif(o) : o /*null or undefined*/;
142
- const toPublicObj = o => o ? o.Q ? o : PublicKey.fromString(o) : o /*null or undefined*/;
143
- const toLongObj = o => o ? Long.isLong(o) ? o : Long.fromString(o) : o;
144
- const toBinaryBuffer = o => o ? Buffer.isBuffer(o) ? o : new Buffer.from(o, 'binary') : o;
145
- module.exports = {
146
- encrypt,
147
- decrypt
148
- };
@@ -1,13 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.normalize = normalize;
7
- function normalize(brain_key) {
8
- if (typeof brain_key !== 'string') {
9
- throw new Error("string required for brain_key");
10
- }
11
- brain_key = brain_key.trim();
12
- return brain_key.split(/[\t\n\v\f\r ]+/).join(' ');
13
- }