-
Notifications
You must be signed in to change notification settings - Fork 500
/
base.js
100 lines (89 loc) · 2.75 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const sjcl = require('./utils').sjcl;
const extend = require('extend');
const Base = {};
// Someone might be using these :)
Base.alphabets = {
ripple: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz',
tipple: 'RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz',
bitcoin: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
};
const {encode, decode} = require('ripple-address-codec');
extend(Base, {
VER_NONE: 1,
VER_NODE_PUBLIC: 28,
VER_NODE_PRIVATE: 32,
VER_ACCOUNT_ID: 0,
VER_ACCOUNT_PUBLIC: 35,
VER_ACCOUNT_PRIVATE: 34,
VER_FAMILY_GENERATOR: 41,
VER_FAMILY_SEED: 33,
VER_ED25519_SEED: [0x01, 0xE1, 0x4B]
});
// --> input: big-endian array of bytes.
// <-- string at least as long as input.
Base.encode = function(input, alphabet) {
return encode(input, {alphabet});
};
// --> input: String
// <-- array of bytes or undefined.
Base.decode = function(input, alphabet) {
if (typeof input !== 'string') {
return undefined;
}
try {
return decode(input, {alphabet});
} catch (e) {
return undefined;
}
};
// --> input: Array
// <-- String
Base.encode_check = function(version, input, alphabet) {
return encode(input, {version, alphabet});
};
// --> input : String
// <-- NaN || sjcl.bn
Base.decode_check = function(version, input, alphabet) {
try {
const decoded = decode(input, {version, alphabet});
return sjcl.bn.fromBits(sjcl.codec.bytes.toBits(decoded));
} catch (e) {
return NaN;
}
};
/**
*
* Decodes (with check) `input` into `expectedLength` number of bytes, trying
* multiple possible `versions`.
*
*
* @param {Array} versions - Array of possible versions. Each element can be
* an array of bytes, or just a single byte
* @param {String} input - the base58 encoded input
* @param {Number} expectedLength - of decoded bytes
* @param {String} [alphabet='ripple'] - name of alphabet to use. eg. 'bitcoin'
*
* If decoded bytes is not the `expectedLength` or none of the `versions`
* matched, will return struct with null members.
*
* @return {Object} result - struct
* @return {sjcl.bn} result.value - sjcl.bn interpretation of decoded bytes
* @return {Array|Number} result.version - the matching element from `versions`
* param
*/
Base.decode_multi_versioned = function(versions, input, expectedLength,
alphabet) {
try {
// Will return valid struct or throw
const {bytes, version} = decode(input, {versions, expectedLength,
alphabet});
return {
version,
value: sjcl.bn.fromBits(sjcl.codec.bytes.toBits(bytes))
};
} catch (e) {
return {value: null, version: null};
}
};
exports.Base = Base;