mirror of
https://github.com/Xahau/xahau.js.git
synced 2025-11-21 04:35:49 +00:00
Initial change from Babel/JS to TypeScript (#70)
* will compile as typescript * migrated test suite to use JestJS * Migrated to Jest testing framework and typescript source files * updated deps * updated prepublish * resolved 1 failing test * changed decimal .0 on four tests, it appears that these were the only four tests expecting integer values to have '.0' * added linter * added package-lock * removed tslint in favor of eslint * changed yarn to npm * updated version 2.6->3.0 * removing package lock * updated node version in nvmrc and jest version in package * removed nvmrc * removed some unused functions * replaced data driven with file from master * commitint yarn.lock * removing babel as a dependency in favor of typescript compiling to es5 * removing babel deps * resolved testing issues by migrating helper function * added partial linting functionality for test suite * updated imports for decodeLedgerData * updated test * updated yarn.lock * removed a console.log * added eslint-jest-plugin to package * reverting to old linting, will add linting in next PR * removed comments in shamap * re-adding .nvmrc * npm -> yarn * added . to .eslintrc * added .eslintrc * removing linting for this PR * Changed linting to print a message so that linting doesnt fail in CI * changing back * added newline so diff wont show * removed eslint deps, since linting will be dealt with in a later PR * changed function calls to describe(...)
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
/* eslint-disable func-style */
|
||||
|
||||
const BN = require('bn.js');
|
||||
const types = require('./types');
|
||||
const {HashPrefix} = require('./hash-prefixes');
|
||||
import { BN } from 'bn.js';
|
||||
import { coreTypes } from './types';
|
||||
const { HashPrefix } = require('./hash-prefixes');
|
||||
const {BinaryParser} = require('./serdes/binary-parser');
|
||||
const {BinarySerializer, BytesList} = require('./serdes/binary-serializer');
|
||||
const {bytesToHex, slice, parseBytes} = require('./utils/bytes-utils');
|
||||
@@ -10,17 +10,17 @@ const {bytesToHex, slice, parseBytes} = require('./utils/bytes-utils');
|
||||
const {sha512Half, transactionID} = require('./hashes');
|
||||
|
||||
const makeParser = bytes => new BinaryParser(bytes);
|
||||
const readJSON = parser => parser.readType(types.STObject).toJSON();
|
||||
const readJSON = parser => parser.readType(coreTypes.STObject).toJSON();
|
||||
const binaryToJSON = bytes => readJSON(makeParser(bytes));
|
||||
|
||||
function serializeObject(object, opts = {}) {
|
||||
function serializeObject(object, opts = <any>{}) {
|
||||
const {prefix, suffix, signingFieldsOnly = false} = opts;
|
||||
const bytesList = new BytesList();
|
||||
if (prefix) {
|
||||
bytesList.put(prefix);
|
||||
}
|
||||
const filter = signingFieldsOnly ? f => f.isSigningField : undefined;
|
||||
types.STObject.from(object).toBytesSink(bytesList, filter);
|
||||
coreTypes.STObject.from(object).toBytesSink(bytesList, filter);
|
||||
if (suffix) {
|
||||
bytesList.put(suffix);
|
||||
}
|
||||
@@ -33,8 +33,8 @@ function signingData(tx, prefix = HashPrefix.transactionSig) {
|
||||
|
||||
function signingClaimData(claim) {
|
||||
const prefix = HashPrefix.paymentChannelClaim
|
||||
const channel = types.Hash256.from(claim.channel).toBytes()
|
||||
const amount = new types.UInt64(new BN(claim.amount)).toBytes();
|
||||
const channel = coreTypes.Hash256.from(claim.channel).toBytes()
|
||||
const amount = new coreTypes.UInt64(new BN(claim.amount)).toBytes();
|
||||
|
||||
const bytesList = new BytesList();
|
||||
|
||||
@@ -46,11 +46,11 @@ function signingClaimData(claim) {
|
||||
|
||||
function multiSigningData(tx, signingAccount) {
|
||||
const prefix = HashPrefix.transactionMultiSig;
|
||||
const suffix = types.AccountID.from(signingAccount).toBytes();
|
||||
const suffix = coreTypes.AccountID.from(signingAccount).toBytes();
|
||||
return serializeObject(tx, {prefix, suffix, signingFieldsOnly: true});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
BinaryParser,
|
||||
BinarySerializer,
|
||||
BytesList,
|
||||
@@ -1,6 +1,5 @@
|
||||
const _ = require('lodash');
|
||||
const enums = require('./enums');
|
||||
const {Field} = enums;
|
||||
import { Enums } from './enums';
|
||||
const {Field} = Enums.Field;
|
||||
const types = require('./types');
|
||||
const binary = require('./binary');
|
||||
const {ShaMap} = require('./shamap');
|
||||
@@ -10,14 +9,14 @@ const quality = require('./quality');
|
||||
const {HashPrefix} = require('./hash-prefixes');
|
||||
|
||||
|
||||
module.exports = _.assign({
|
||||
hashes: _.assign({}, hashes, ledgerHashes),
|
||||
export {
|
||||
hashes,
|
||||
binary,
|
||||
enums,
|
||||
ledgerHashes,
|
||||
Enums,
|
||||
quality,
|
||||
Field,
|
||||
HashPrefix,
|
||||
ShaMap
|
||||
},
|
||||
ShaMap,
|
||||
types
|
||||
);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const _ = require('lodash');
|
||||
const {parseBytes, serializeUIntN} = require('./../utils/bytes-utils');
|
||||
const makeClass = require('./../utils/make-class');
|
||||
const enums = require('./definitions.json');
|
||||
|
||||
function transformWith(func, obj) {
|
||||
return _.transform(obj, func);
|
||||
}
|
||||
|
||||
function biMap(obj, valueKey) {
|
||||
return _.transform(obj, (result, value, key) => {
|
||||
result[key] = value;
|
||||
result[value[valueKey]] = value;
|
||||
});
|
||||
}
|
||||
|
||||
const EnumType = makeClass({
|
||||
EnumType(definition) {
|
||||
_.assign(this, definition);
|
||||
// At minimum
|
||||
assert(this.bytes instanceof Uint8Array);
|
||||
assert(typeof this.ordinal === 'number');
|
||||
assert(typeof this.name === 'string');
|
||||
},
|
||||
toString() {
|
||||
return this.name;
|
||||
},
|
||||
toJSON() {
|
||||
return this.name;
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
sink.put(this.bytes);
|
||||
},
|
||||
statics: {
|
||||
ordinalByteWidth: 1,
|
||||
fromParser(parser) {
|
||||
return this.from(parser.readUIntN(this.ordinalByteWidth));
|
||||
},
|
||||
from(val) {
|
||||
const ret = val instanceof this ? val : this[val];
|
||||
if (!ret) {
|
||||
throw new Error(
|
||||
`${val} is not a valid name or ordinal for ${this.enumName}`);
|
||||
}
|
||||
return ret;
|
||||
},
|
||||
valuesByName() {
|
||||
return _.transform(this.initVals, (result, ordinal, name) => {
|
||||
const bytes = serializeUIntN(ordinal, this.ordinalByteWidth);
|
||||
const type = new this({name, ordinal, bytes});
|
||||
result[name] = type;
|
||||
});
|
||||
},
|
||||
init() {
|
||||
const mapped = this.valuesByName();
|
||||
_.assign(this, biMap(mapped, 'ordinal'));
|
||||
this.values = _.values(mapped);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function makeEnum(name, definition) {
|
||||
return makeClass({
|
||||
inherits: EnumType,
|
||||
statics: _.assign(definition, {enumName: name})
|
||||
});
|
||||
}
|
||||
|
||||
function makeEnums(to, definition, name) {
|
||||
to[name] = makeEnum(name, definition);
|
||||
}
|
||||
|
||||
const Enums = transformWith(makeEnums, {
|
||||
Type: {
|
||||
initVals: enums.TYPES
|
||||
},
|
||||
LedgerEntryType: {
|
||||
initVals: enums.LEDGER_ENTRY_TYPES, ordinalByteWidth: 2
|
||||
},
|
||||
TransactionType: {
|
||||
initVals: enums.TRANSACTION_TYPES, ordinalByteWidth: 2
|
||||
},
|
||||
TransactionResult: {
|
||||
initVals: enums.TRANSACTION_RESULTS, ordinalByteWidth: 1
|
||||
}
|
||||
});
|
||||
|
||||
Enums.Field = makeClass({
|
||||
inherits: EnumType,
|
||||
statics: {
|
||||
enumName: 'Field',
|
||||
initVals: enums.FIELDS,
|
||||
valuesByName() {
|
||||
const fields = _.map(this.initVals, ([name, definition]) => {
|
||||
const type = Enums.Type[definition.type];
|
||||
const bytes = this.header(type.ordinal, definition.nth);
|
||||
const ordinal = type.ordinal << 16 | definition.nth;
|
||||
const extra = {ordinal, name, type, bytes};
|
||||
return new this(_.assign(definition, extra));
|
||||
});
|
||||
return _.keyBy(fields, 'name');
|
||||
},
|
||||
header(type, nth) {
|
||||
const name = nth;
|
||||
const header = [];
|
||||
const push = header.push.bind(header);
|
||||
if (type < 16) {
|
||||
if (name < 16) {
|
||||
push(type << 4 | name);
|
||||
} else {
|
||||
push(type << 4, name);
|
||||
}
|
||||
} else if (name < 16) {
|
||||
push(name, type);
|
||||
} else {
|
||||
push(0, type, name);
|
||||
}
|
||||
return parseBytes(header, Uint8Array);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = Enums;
|
||||
125
packages/ripple-binary-codec/src/enums/index.ts
Normal file
125
packages/ripple-binary-codec/src/enums/index.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { makeClass } from './../utils/make-class'
|
||||
const assert = require('assert')
|
||||
const _ = require('lodash')
|
||||
const { parseBytes, serializeUIntN } = require('./../utils/bytes-utils')
|
||||
const enums = require('./definitions.json')
|
||||
|
||||
function transformWith (func, obj) {
|
||||
return _.transform(obj, func)
|
||||
}
|
||||
|
||||
function biMap (obj, valueKey) {
|
||||
return _.transform(obj, (result, value, key) => {
|
||||
result[key] = value
|
||||
result[value[valueKey]] = value
|
||||
})
|
||||
}
|
||||
|
||||
const EnumType = makeClass({
|
||||
EnumType (definition) {
|
||||
_.assign(this, definition)
|
||||
// At minimum
|
||||
assert(this.bytes instanceof Uint8Array)
|
||||
assert(typeof this.ordinal === 'number')
|
||||
assert(typeof this.name === 'string')
|
||||
},
|
||||
toString () {
|
||||
return this.name
|
||||
},
|
||||
toJSON () {
|
||||
return this.name
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
sink.put(this.bytes)
|
||||
},
|
||||
statics: {
|
||||
ordinalByteWidth: 1,
|
||||
fromParser (parser) {
|
||||
return this.from(parser.readUIntN(this.ordinalByteWidth))
|
||||
},
|
||||
from (val) {
|
||||
const ret = val instanceof this ? val : this[val]
|
||||
if (!ret) {
|
||||
throw new Error(
|
||||
`${val} is not a valid name or ordinal for ${this.enumName}`)
|
||||
}
|
||||
return ret
|
||||
},
|
||||
valuesByName () {
|
||||
return _.transform(this.initVals, (result, ordinal, name) => {
|
||||
const bytes = serializeUIntN(ordinal, this.ordinalByteWidth)
|
||||
const type = new this({ name, ordinal, bytes })
|
||||
result[name] = type
|
||||
})
|
||||
},
|
||||
init () {
|
||||
const mapped = this.valuesByName()
|
||||
_.assign(this, biMap(mapped, 'ordinal'))
|
||||
this.values = _.values(mapped)
|
||||
return this
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
function makeEnum (name, definition) {
|
||||
return makeClass({
|
||||
inherits: EnumType,
|
||||
statics: _.assign(definition, { enumName: name })
|
||||
}, undefined)
|
||||
}
|
||||
|
||||
function makeEnums (to, definition, name) {
|
||||
to[name] = makeEnum(name, definition)
|
||||
}
|
||||
|
||||
const Enums = transformWith(makeEnums, {
|
||||
Type: {
|
||||
initVals: enums.TYPES
|
||||
},
|
||||
LedgerEntryType: {
|
||||
initVals: enums.LEDGER_ENTRY_TYPES, ordinalByteWidth: 2
|
||||
},
|
||||
TransactionType: {
|
||||
initVals: enums.TRANSACTION_TYPES, ordinalByteWidth: 2
|
||||
},
|
||||
TransactionResult: {
|
||||
initVals: enums.TRANSACTION_RESULTS, ordinalByteWidth: 1
|
||||
}
|
||||
})
|
||||
|
||||
Enums.Field = makeClass({
|
||||
inherits: EnumType,
|
||||
statics: {
|
||||
enumName: 'Field',
|
||||
initVals: enums.FIELDS,
|
||||
valuesByName () {
|
||||
const fields = _.map(this.initVals, ([name, definition]) => {
|
||||
const type = Enums.Type[definition.type]
|
||||
const bytes = this.header(type.ordinal, definition.nth)
|
||||
const ordinal = type.ordinal << 16 | definition.nth
|
||||
const extra = { ordinal, name, type, bytes }
|
||||
return new this(_.assign(definition, extra))
|
||||
})
|
||||
return _.keyBy(fields, 'name')
|
||||
},
|
||||
header (type, nth) {
|
||||
const name = nth
|
||||
const header = <any>[]
|
||||
const push = header.push.bind(header)
|
||||
if (type < 16) {
|
||||
if (name < 16) {
|
||||
push(type << 4 | name)
|
||||
} else {
|
||||
push(type << 4, name)
|
||||
}
|
||||
} else if (name < 16) {
|
||||
push(name, type)
|
||||
} else {
|
||||
push(0, type, name)
|
||||
}
|
||||
return parseBytes(header, Uint8Array)
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export { Enums }
|
||||
@@ -1,134 +0,0 @@
|
||||
/**
|
||||
* Quick script to re-number values
|
||||
*/
|
||||
|
||||
const input = {
|
||||
'temBAD_SEND_XRP_PATHS': -283,
|
||||
'temBAD_SEQUENCE': -282,
|
||||
'temBAD_SIGNATURE': -281,
|
||||
'temBAD_SRC_ACCOUNT': -280,
|
||||
'temBAD_TRANSFER_RATE': -279,
|
||||
'temDST_IS_SRC': -278,
|
||||
'temDST_NEEDED': -277,
|
||||
'temINVALID': -276,
|
||||
'temINVALID_FLAG': -275,
|
||||
'temREDUNDANT': -274,
|
||||
'temRIPPLE_EMPTY': -273,
|
||||
'temDISABLED': -272,
|
||||
'temBAD_SIGNER': -271,
|
||||
'temBAD_QUORUM': -270,
|
||||
'temBAD_WEIGHT': -269,
|
||||
'temBAD_TICK_SIZE': -268,
|
||||
'temINVALID_ACCOUNT_ID': -267,
|
||||
'temCANNOT_PREAUTH_SELF': -266,
|
||||
|
||||
'temUNCERTAIN': -265,
|
||||
'temUNKNOWN': -264,
|
||||
|
||||
'tefFAILURE': -199,
|
||||
'tefALREADY': -198,
|
||||
'tefBAD_ADD_AUTH': -197,
|
||||
'tefBAD_AUTH': -196,
|
||||
'tefBAD_LEDGER': -195,
|
||||
'tefCREATED': -194,
|
||||
'tefEXCEPTION': -193,
|
||||
'tefINTERNAL': -192,
|
||||
'tefNO_AUTH_REQUIRED': -191,
|
||||
'tefPAST_SEQ': -190,
|
||||
'tefWRONG_PRIOR': -189,
|
||||
'tefMASTER_DISABLED': -188,
|
||||
'tefMAX_LEDGER': -187,
|
||||
'tefBAD_SIGNATURE': -186,
|
||||
'tefBAD_QUORUM': -185,
|
||||
'tefNOT_MULTI_SIGNING': -184,
|
||||
'tefBAD_AUTH_MASTER': -183,
|
||||
'tefINVARIANT_FAILED': -182,
|
||||
'tefTOO_BIG': -181,
|
||||
|
||||
'terRETRY': -99,
|
||||
'terFUNDS_SPENT': -98,
|
||||
'terINSUF_FEE_B': -97,
|
||||
'terNO_ACCOUNT': -96,
|
||||
'terNO_AUTH': -95,
|
||||
'terNO_LINE': -94,
|
||||
'terOWNERS': -93,
|
||||
'terPRE_SEQ': -92,
|
||||
'terLAST': -91,
|
||||
'terNO_RIPPLE': -90,
|
||||
'terQUEUED': -89,
|
||||
|
||||
'tesSUCCESS': 0,
|
||||
|
||||
'tecCLAIM': 100,
|
||||
'tecPATH_PARTIAL': 101,
|
||||
'tecUNFUNDED_ADD': 102,
|
||||
'tecUNFUNDED_OFFER': 103,
|
||||
'tecUNFUNDED_PAYMENT': 104,
|
||||
'tecFAILED_PROCESSING': 105,
|
||||
'tecDIR_FULL': 121,
|
||||
'tecINSUF_RESERVE_LINE': 122,
|
||||
'tecINSUF_RESERVE_OFFER': 123,
|
||||
'tecNO_DST': 124,
|
||||
'tecNO_DST_INSUF_XRP': 125,
|
||||
'tecNO_LINE_INSUF_RESERVE': 126,
|
||||
'tecNO_LINE_REDUNDANT': 127,
|
||||
'tecPATH_DRY': 128,
|
||||
'tecUNFUNDED': 129,
|
||||
'tecNO_ALTERNATIVE_KEY': 130,
|
||||
'tecNO_REGULAR_KEY': 131,
|
||||
'tecOWNERS': 132,
|
||||
'tecNO_ISSUER': 133,
|
||||
'tecNO_AUTH': 134,
|
||||
'tecNO_LINE': 135,
|
||||
'tecINSUFF_FEE': 136,
|
||||
'tecFROZEN': 137,
|
||||
'tecNO_TARGET': 138,
|
||||
'tecNO_PERMISSION': 139,
|
||||
'tecNO_ENTRY': 140,
|
||||
'tecINSUFFICIENT_RESERVE': 141,
|
||||
'tecNEED_MASTER_KEY': 142,
|
||||
'tecDST_TAG_NEEDED': 143,
|
||||
'tecINTERNAL': 144,
|
||||
'tecOVERSIZE': 145,
|
||||
'tecCRYPTOCONDITION_ERROR': 146,
|
||||
'tecINVARIANT_FAILED': 147,
|
||||
'tecEXPIRED': 148,
|
||||
'tecDUPLICATE': 149,
|
||||
'tecKILLED': 150,
|
||||
'tecHAS_OBLIGATIONS': 151,
|
||||
'tecTOO_SOON': 152
|
||||
};
|
||||
|
||||
let starting_from_temBAD_SEND_XRP_PATHS = -284;
|
||||
|
||||
let starting_from_tefFAILURE = -199;
|
||||
|
||||
let starting_from_terRETRY = -99;
|
||||
|
||||
const tesSUCCESS = 0;
|
||||
|
||||
let starting_from_tecCLAIM = 100;
|
||||
|
||||
const starting_from_tecDIR_FULL = 121;
|
||||
|
||||
let previousKey = 'tem';
|
||||
Object.keys(input).forEach(key => {
|
||||
if (key.substring(0, 3) !== previousKey.substring(0, 3)) {
|
||||
console.log();
|
||||
previousKey = key;
|
||||
}
|
||||
if (key.substring(0, 3) === 'tem') {
|
||||
console.log(` "${key}": ${starting_from_temBAD_SEND_XRP_PATHS++},`);
|
||||
} else if (key.substring(0, 3) === 'tef') {
|
||||
console.log(` "${key}": ${starting_from_tefFAILURE++},`);
|
||||
} else if (key.substring(0, 3) === 'ter') {
|
||||
console.log(` "${key}": ${starting_from_terRETRY++},`);
|
||||
} else if (key.substring(0, 3) === 'tes') {
|
||||
console.log(` "${key}": ${tesSUCCESS},`);
|
||||
} else if (key.substring(0, 3) === 'tec') {
|
||||
if (key === 'tecDIR_FULL') {
|
||||
starting_from_tecCLAIM = starting_from_tecDIR_FULL;
|
||||
}
|
||||
console.log(` "${key}": ${starting_from_tecCLAIM++},`);
|
||||
}
|
||||
});
|
||||
134
packages/ripple-binary-codec/src/enums/utils-renumber.ts
Normal file
134
packages/ripple-binary-codec/src/enums/utils-renumber.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Quick script to re-number values
|
||||
*/
|
||||
|
||||
const input = {
|
||||
temBAD_SEND_XRP_PATHS: -283,
|
||||
temBAD_SEQUENCE: -282,
|
||||
temBAD_SIGNATURE: -281,
|
||||
temBAD_SRC_ACCOUNT: -280,
|
||||
temBAD_TRANSFER_RATE: -279,
|
||||
temDST_IS_SRC: -278,
|
||||
temDST_NEEDED: -277,
|
||||
temINVALID: -276,
|
||||
temINVALID_FLAG: -275,
|
||||
temREDUNDANT: -274,
|
||||
temRIPPLE_EMPTY: -273,
|
||||
temDISABLED: -272,
|
||||
temBAD_SIGNER: -271,
|
||||
temBAD_QUORUM: -270,
|
||||
temBAD_WEIGHT: -269,
|
||||
temBAD_TICK_SIZE: -268,
|
||||
temINVALID_ACCOUNT_ID: -267,
|
||||
temCANNOT_PREAUTH_SELF: -266,
|
||||
|
||||
temUNCERTAIN: -265,
|
||||
temUNKNOWN: -264,
|
||||
|
||||
tefFAILURE: -199,
|
||||
tefALREADY: -198,
|
||||
tefBAD_ADD_AUTH: -197,
|
||||
tefBAD_AUTH: -196,
|
||||
tefBAD_LEDGER: -195,
|
||||
tefCREATED: -194,
|
||||
tefEXCEPTION: -193,
|
||||
tefINTERNAL: -192,
|
||||
tefNO_AUTH_REQUIRED: -191,
|
||||
tefPAST_SEQ: -190,
|
||||
tefWRONG_PRIOR: -189,
|
||||
tefMASTER_DISABLED: -188,
|
||||
tefMAX_LEDGER: -187,
|
||||
tefBAD_SIGNATURE: -186,
|
||||
tefBAD_QUORUM: -185,
|
||||
tefNOT_MULTI_SIGNING: -184,
|
||||
tefBAD_AUTH_MASTER: -183,
|
||||
tefINVARIANT_FAILED: -182,
|
||||
tefTOO_BIG: -181,
|
||||
|
||||
terRETRY: -99,
|
||||
terFUNDS_SPENT: -98,
|
||||
terINSUF_FEE_B: -97,
|
||||
terNO_ACCOUNT: -96,
|
||||
terNO_AUTH: -95,
|
||||
terNO_LINE: -94,
|
||||
terOWNERS: -93,
|
||||
terPRE_SEQ: -92,
|
||||
terLAST: -91,
|
||||
terNO_RIPPLE: -90,
|
||||
terQUEUED: -89,
|
||||
|
||||
tesSUCCESS: 0,
|
||||
|
||||
tecCLAIM: 100,
|
||||
tecPATH_PARTIAL: 101,
|
||||
tecUNFUNDED_ADD: 102,
|
||||
tecUNFUNDED_OFFER: 103,
|
||||
tecUNFUNDED_PAYMENT: 104,
|
||||
tecFAILED_PROCESSING: 105,
|
||||
tecDIR_FULL: 121,
|
||||
tecINSUF_RESERVE_LINE: 122,
|
||||
tecINSUF_RESERVE_OFFER: 123,
|
||||
tecNO_DST: 124,
|
||||
tecNO_DST_INSUF_XRP: 125,
|
||||
tecNO_LINE_INSUF_RESERVE: 126,
|
||||
tecNO_LINE_REDUNDANT: 127,
|
||||
tecPATH_DRY: 128,
|
||||
tecUNFUNDED: 129,
|
||||
tecNO_ALTERNATIVE_KEY: 130,
|
||||
tecNO_REGULAR_KEY: 131,
|
||||
tecOWNERS: 132,
|
||||
tecNO_ISSUER: 133,
|
||||
tecNO_AUTH: 134,
|
||||
tecNO_LINE: 135,
|
||||
tecINSUFF_FEE: 136,
|
||||
tecFROZEN: 137,
|
||||
tecNO_TARGET: 138,
|
||||
tecNO_PERMISSION: 139,
|
||||
tecNO_ENTRY: 140,
|
||||
tecINSUFFICIENT_RESERVE: 141,
|
||||
tecNEED_MASTER_KEY: 142,
|
||||
tecDST_TAG_NEEDED: 143,
|
||||
tecINTERNAL: 144,
|
||||
tecOVERSIZE: 145,
|
||||
tecCRYPTOCONDITION_ERROR: 146,
|
||||
tecINVARIANT_FAILED: 147,
|
||||
tecEXPIRED: 148,
|
||||
tecDUPLICATE: 149,
|
||||
tecKILLED: 150,
|
||||
tecHAS_OBLIGATIONS: 151,
|
||||
tecTOO_SOON: 152
|
||||
}
|
||||
|
||||
let startingFromTemBADSENDXRPPATHS = -284
|
||||
|
||||
let startingFromTefFAILURE = -199
|
||||
|
||||
let startingFromTerRETRY = -99
|
||||
|
||||
const tesSUCCESS = 0
|
||||
|
||||
let startingFromTecCLAIM = 100
|
||||
|
||||
const startingFromTecDIRFULL = 121
|
||||
|
||||
let previousKey = 'tem'
|
||||
Object.keys(input).forEach(key => {
|
||||
if (key.substring(0, 3) !== previousKey.substring(0, 3)) {
|
||||
console.log()
|
||||
previousKey = key
|
||||
}
|
||||
if (key.substring(0, 3) === 'tem') {
|
||||
console.log(` "${key}": ${startingFromTemBADSENDXRPPATHS++},`)
|
||||
} else if (key.substring(0, 3) === 'tef') {
|
||||
console.log(` "${key}": ${startingFromTefFAILURE++},`)
|
||||
} else if (key.substring(0, 3) === 'ter') {
|
||||
console.log(` "${key}": ${startingFromTerRETRY++},`)
|
||||
} else if (key.substring(0, 3) === 'tes') {
|
||||
console.log(` "${key}": ${tesSUCCESS},`)
|
||||
} else if (key.substring(0, 3) === 'tec') {
|
||||
if (key === 'tecDIR_FULL') {
|
||||
startingFromTecCLAIM = startingFromTecDIRFULL
|
||||
}
|
||||
console.log(` "${key}": ${startingFromTecCLAIM++},`)
|
||||
}
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
const {serializeUIntN} = require('./utils/bytes-utils');
|
||||
import { serializeUIntN } from './utils/bytes-utils';
|
||||
|
||||
function bytes(uint32) {
|
||||
return serializeUIntN(uint32, 4);
|
||||
@@ -26,6 +26,6 @@ const HashPrefix = {
|
||||
paymentChannelClaim: bytes(0x434C4D00)
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
HashPrefix
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
const makeClass = require('./utils/make-class');
|
||||
const {HashPrefix} = require('./hash-prefixes');
|
||||
const {Hash256} = require('./types');
|
||||
const {parseBytes} = require('./utils/bytes-utils');
|
||||
const createHash = require('create-hash');
|
||||
import { makeClass } from './utils/make-class';
|
||||
import { HashPrefix } from './hash-prefixes';
|
||||
import { coreTypes } from './types';
|
||||
import { parseBytes } from './utils/bytes-utils';
|
||||
import * as createHash from 'create-hash';
|
||||
|
||||
const Sha512Half = makeClass({
|
||||
Sha512Half() {
|
||||
@@ -22,9 +22,9 @@ const Sha512Half = makeClass({
|
||||
return bytes.slice(0, 32);
|
||||
},
|
||||
finish() {
|
||||
return new Hash256(this.finish256());
|
||||
return new coreTypes.Hash256(this.finish256());
|
||||
}
|
||||
});
|
||||
}, undefined);
|
||||
|
||||
function sha512Half(...args) {
|
||||
const hash = new Sha512Half();
|
||||
@@ -33,10 +33,10 @@ function sha512Half(...args) {
|
||||
}
|
||||
|
||||
function transactionID(serialized) {
|
||||
return new Hash256(sha512Half(HashPrefix.transactionID, serialized));
|
||||
return new coreTypes.Hash256(sha512Half(HashPrefix.transactionID, serialized));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
Sha512Half,
|
||||
sha512Half,
|
||||
transactionID
|
||||
@@ -1,13 +1,14 @@
|
||||
const assert = require('assert');
|
||||
const coreTypes = require('./coretypes');
|
||||
const {quality,
|
||||
binary: {bytesToHex,
|
||||
signingData,
|
||||
signingClaimData,
|
||||
multiSigningData,
|
||||
binaryToJSON,
|
||||
serializeObject,
|
||||
BinaryParser}} = coreTypes;
|
||||
import {strict as assert} from 'assert';
|
||||
import { quality, binary } from './coretypes';
|
||||
import { coreTypes } from './types';
|
||||
const { bytesToHex,
|
||||
signingData,
|
||||
signingClaimData,
|
||||
multiSigningData,
|
||||
binaryToJSON,
|
||||
serializeObject,
|
||||
BinaryParser } = binary;
|
||||
|
||||
|
||||
function decodeLedgerData(binary) {
|
||||
assert(typeof binary === 'string', 'binary must be a hex string');
|
||||
@@ -70,4 +71,4 @@ module.exports = {
|
||||
encodeQuality,
|
||||
decodeQuality,
|
||||
decodeLedgerData
|
||||
};
|
||||
};
|
||||
@@ -1,12 +1,12 @@
|
||||
const _ = require('lodash');
|
||||
const BN = require('bn.js');
|
||||
const assert = require('assert');
|
||||
const types = require('./types');
|
||||
const {STObject, Hash256} = types;
|
||||
const {ShaMap} = require('./shamap');
|
||||
const {HashPrefix} = require('./hash-prefixes');
|
||||
const {Sha512Half} = require('./hashes');
|
||||
const {BinarySerializer, serializeObject} = require('./binary');
|
||||
import * as _ from 'lodash'
|
||||
import { BN } from 'bn.js';
|
||||
import { strict as assert } from 'assert';
|
||||
import { coreTypes } from './types';
|
||||
const { STObject, Hash256 } = coreTypes;
|
||||
import { ShaMap } from './shamap';
|
||||
import { HashPrefix } from './hash-prefixes';
|
||||
import { Sha512Half } from './hashes';
|
||||
import { BinarySerializer, serializeObject } from './binary';
|
||||
|
||||
function computeHash(itemizer, itemsJson) {
|
||||
const map = new ShaMap();
|
||||
@@ -53,19 +53,19 @@ function ledgerHash(header) {
|
||||
assert(header.parent_close_time !== undefined);
|
||||
assert(header.close_flags !== undefined);
|
||||
|
||||
types.UInt32.from(header.ledger_index).toBytesSink(hash);
|
||||
types.UInt64.from(new BN(header.total_coins)).toBytesSink(hash);
|
||||
types.Hash256.from(header.parent_hash).toBytesSink(hash);
|
||||
types.Hash256.from(header.transaction_hash).toBytesSink(hash);
|
||||
types.Hash256.from(header.account_hash).toBytesSink(hash);
|
||||
types.UInt32.from(header.parent_close_time).toBytesSink(hash);
|
||||
types.UInt32.from(header.close_time).toBytesSink(hash);
|
||||
types.UInt8.from(header.close_time_resolution).toBytesSink(hash);
|
||||
types.UInt8.from(header.close_flags).toBytesSink(hash);
|
||||
coreTypes.UInt32.from(header.ledger_index).toBytesSink(hash);
|
||||
coreTypes.UInt64.from(new BN(header.total_coins)).toBytesSink(hash);
|
||||
coreTypes.Hash256.from(header.parent_hash).toBytesSink(hash);
|
||||
coreTypes.Hash256.from(header.transaction_hash).toBytesSink(hash);
|
||||
coreTypes.Hash256.from(header.account_hash).toBytesSink(hash);
|
||||
coreTypes.UInt32.from(header.parent_close_time).toBytesSink(hash);
|
||||
coreTypes.UInt32.from(header.close_time).toBytesSink(hash);
|
||||
coreTypes.UInt8.from(header.close_time_resolution).toBytesSink(hash);
|
||||
coreTypes.UInt8.from(header.close_flags).toBytesSink(hash);
|
||||
return hash.finish();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
accountStateHash,
|
||||
transactionTreeHash,
|
||||
ledgerHash
|
||||
@@ -1,14 +1,14 @@
|
||||
const Decimal = require('decimal.js');
|
||||
const {bytesToHex, slice, parseBytes} = require('./utils/bytes-utils');
|
||||
const {UInt64} = require('./types');
|
||||
const BN = require('bn.js');
|
||||
import { bytesToHex, slice, parseBytes } from './utils/bytes-utils';
|
||||
import { coreTypes } from './types';
|
||||
import { BN } from 'bn.js';
|
||||
|
||||
module.exports = {
|
||||
encode(arg) {
|
||||
const quality = arg instanceof Decimal ? arg : new Decimal(arg);
|
||||
const exponent = quality.e - 15;
|
||||
const qualityString = quality.times('1e' + -exponent).abs().toString();
|
||||
const bytes = new UInt64(new BN(qualityString)).toBytes();
|
||||
const bytes = new coreTypes.UInt64(new BN(qualityString)).toBytes();
|
||||
bytes[0] = exponent + 100;
|
||||
return bytes;
|
||||
},
|
||||
@@ -1,99 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Field} = require('../enums');
|
||||
const {slice, parseBytes} = require('../utils/bytes-utils');
|
||||
|
||||
const BinaryParser = makeClass({
|
||||
BinaryParser(buf) {
|
||||
this._buf = parseBytes(buf, Uint8Array);
|
||||
this._length = this._buf.length;
|
||||
this._cursor = 0;
|
||||
},
|
||||
skip(n) {
|
||||
this._cursor += n;
|
||||
},
|
||||
read(n, to = Uint8Array) {
|
||||
const start = this._cursor;
|
||||
const end = this._cursor + n;
|
||||
assert(end <= this._buf.length);
|
||||
this._cursor = end;
|
||||
return slice(this._buf, start, end, to);
|
||||
},
|
||||
readUIntN(n) {
|
||||
return this.read(n, Array).reduce((a, b) => a << 8 | b) >>> 0;
|
||||
},
|
||||
readUInt8() {
|
||||
return this._buf[this._cursor++];
|
||||
},
|
||||
readUInt16() {
|
||||
return this.readUIntN(2);
|
||||
},
|
||||
readUInt32() {
|
||||
return this.readUIntN(4);
|
||||
},
|
||||
pos() {
|
||||
return this._cursor;
|
||||
},
|
||||
size() {
|
||||
return this._buf.length;
|
||||
},
|
||||
end(customEnd) {
|
||||
const cursor = this.pos();
|
||||
return (cursor >= this._length) || (customEnd !== null &&
|
||||
cursor >= customEnd);
|
||||
},
|
||||
readVL() {
|
||||
return this.read(this.readVLLength());
|
||||
},
|
||||
readVLLength() {
|
||||
const b1 = this.readUInt8();
|
||||
if (b1 <= 192) {
|
||||
return b1;
|
||||
} else if (b1 <= 240) {
|
||||
const b2 = this.readUInt8();
|
||||
return 193 + (b1 - 193) * 256 + b2;
|
||||
} else if (b1 <= 254) {
|
||||
const b2 = this.readUInt8();
|
||||
const b3 = this.readUInt8();
|
||||
return 12481 + (b1 - 241) * 65536 + b2 * 256 + b3;
|
||||
}
|
||||
throw new Error('Invalid varint length indicator');
|
||||
},
|
||||
readFieldOrdinal() {
|
||||
const tagByte = this.readUInt8();
|
||||
const type = (tagByte & 0xF0) >>> 4 || this.readUInt8();
|
||||
const nth = tagByte & 0x0F || this.readUInt8();
|
||||
return type << 16 | nth;
|
||||
},
|
||||
readField() {
|
||||
return Field.from(this.readFieldOrdinal());
|
||||
},
|
||||
readType(type) {
|
||||
return type.fromParser(this);
|
||||
},
|
||||
typeForField(field) {
|
||||
return field.associatedType;
|
||||
},
|
||||
readFieldValue(field) {
|
||||
const kls = this.typeForField(field);
|
||||
if (!kls) {
|
||||
throw new Error(`unsupported: (${field.name}, ${field.type.name})`);
|
||||
}
|
||||
const sizeHint = field.isVLEncoded ? this.readVLLength() : null;
|
||||
const value = kls.fromParser(this, sizeHint);
|
||||
if (value === undefined) {
|
||||
throw new Error(
|
||||
`fromParser for (${field.name}, ${field.type.name}) -> undefined `);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
readFieldAndValue() {
|
||||
const field = this.readField();
|
||||
return [field, this.readFieldValue(field)];
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = {
|
||||
BinaryParser
|
||||
};
|
||||
98
packages/ripple-binary-codec/src/serdes/binary-parser.ts
Normal file
98
packages/ripple-binary-codec/src/serdes/binary-parser.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { strict as assert } from 'assert'
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Enums } from '../enums'
|
||||
import { slice, parseBytes } from '../utils/bytes-utils'
|
||||
|
||||
const BinaryParser = makeClass({
|
||||
BinaryParser (buf) {
|
||||
this._buf = parseBytes(buf, Uint8Array)
|
||||
this._length = this._buf.length
|
||||
this._cursor = 0
|
||||
},
|
||||
skip (n) {
|
||||
this._cursor += n
|
||||
},
|
||||
read (n, to = Uint8Array) {
|
||||
const start = this._cursor
|
||||
const end = this._cursor + n
|
||||
assert(end <= this._buf.length)
|
||||
this._cursor = end
|
||||
return slice(this._buf, start, end, to)
|
||||
},
|
||||
readUIntN (n) {
|
||||
return this.read(n, Array).reduce((a, b) => a << 8 | b) >>> 0
|
||||
},
|
||||
readUInt8 () {
|
||||
return this._buf[this._cursor++]
|
||||
},
|
||||
readUInt16 () {
|
||||
return this.readUIntN(2)
|
||||
},
|
||||
readUInt32 () {
|
||||
return this.readUIntN(4)
|
||||
},
|
||||
pos () {
|
||||
return this._cursor
|
||||
},
|
||||
size () {
|
||||
return this._buf.length
|
||||
},
|
||||
end (customEnd) {
|
||||
const cursor = this.pos()
|
||||
return (cursor >= this._length) || (customEnd !== null &&
|
||||
cursor >= customEnd)
|
||||
},
|
||||
readVL () {
|
||||
return this.read(this.readVLLength())
|
||||
},
|
||||
readVLLength () {
|
||||
const b1 = this.readUInt8()
|
||||
if (b1 <= 192) {
|
||||
return b1
|
||||
} else if (b1 <= 240) {
|
||||
const b2 = this.readUInt8()
|
||||
return 193 + (b1 - 193) * 256 + b2
|
||||
} else if (b1 <= 254) {
|
||||
const b2 = this.readUInt8()
|
||||
const b3 = this.readUInt8()
|
||||
return 12481 + (b1 - 241) * 65536 + b2 * 256 + b3
|
||||
}
|
||||
throw new Error('Invalid varint length indicator')
|
||||
},
|
||||
readFieldOrdinal () {
|
||||
const tagByte = this.readUInt8()
|
||||
const type = (tagByte & 0xF0) >>> 4 || this.readUInt8()
|
||||
const nth = tagByte & 0x0F || this.readUInt8()
|
||||
return type << 16 | nth
|
||||
},
|
||||
readField () {
|
||||
return Enums.Field.from(this.readFieldOrdinal())
|
||||
},
|
||||
readType (type) {
|
||||
return type.fromParser(this)
|
||||
},
|
||||
typeForField (field) {
|
||||
return field.associatedType
|
||||
},
|
||||
readFieldValue (field) {
|
||||
const kls = this.typeForField(field)
|
||||
if (!kls) {
|
||||
throw new Error(`unsupported: (${field.name}, ${field.type.name})`)
|
||||
}
|
||||
const sizeHint = field.isVLEncoded ? this.readVLLength() : null
|
||||
const value = kls.fromParser(this, sizeHint)
|
||||
if (value === undefined) {
|
||||
throw new Error(
|
||||
`fromParser for (${field.name}, ${field.type.name}) -> undefined `)
|
||||
}
|
||||
return value
|
||||
},
|
||||
readFieldAndValue () {
|
||||
const field = this.readField()
|
||||
return [field, this.readFieldValue(field)]
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
BinaryParser
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const {parseBytes, bytesToHex} = require('../utils/bytes-utils');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Type, Field} = require('../enums');
|
||||
|
||||
const BytesSink = {
|
||||
put(/* bytesSequence */) {
|
||||
// any hex string or any object with a `length` and where 0 <= [ix] <= 255
|
||||
}
|
||||
};
|
||||
|
||||
const BytesList = makeClass({
|
||||
implementing: BytesSink,
|
||||
BytesList() {
|
||||
this.arrays = [];
|
||||
this.length = 0;
|
||||
},
|
||||
put(bytesArg) {
|
||||
const bytes = parseBytes(bytesArg, Uint8Array);
|
||||
this.length += bytes.length;
|
||||
this.arrays.push(bytes);
|
||||
return this;
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
this.arrays.forEach(arr => {
|
||||
sink.put(arr);
|
||||
});
|
||||
},
|
||||
toBytes() {
|
||||
const concatenated = new Uint8Array(this.length);
|
||||
let pointer = 0;
|
||||
this.arrays.forEach(arr => {
|
||||
concatenated.set(arr, pointer);
|
||||
pointer += arr.length;
|
||||
});
|
||||
return concatenated;
|
||||
},
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
}
|
||||
});
|
||||
|
||||
const BinarySerializer = makeClass({
|
||||
BinarySerializer(sink) {
|
||||
this.sink = sink;
|
||||
},
|
||||
write(value) {
|
||||
value.toBytesSink(this.sink);
|
||||
},
|
||||
put(bytes) {
|
||||
this.sink.put(bytes);
|
||||
},
|
||||
writeType(type, value) {
|
||||
this.write(type.from(value));
|
||||
},
|
||||
writeBytesList(bl) {
|
||||
bl.toBytesSink(this.sink);
|
||||
},
|
||||
encodeVL(len) {
|
||||
let length = len;
|
||||
const lenBytes = new Uint8Array(4);
|
||||
if (length <= 192) {
|
||||
lenBytes[0] = length;
|
||||
return lenBytes.subarray(0, 1);
|
||||
} else if (length <= 12480) {
|
||||
length -= 193;
|
||||
lenBytes[0] = 193 + (length >>> 8);
|
||||
lenBytes[1] = length & 0xff;
|
||||
return lenBytes.subarray(0, 2);
|
||||
} else if (length <= 918744) {
|
||||
length -= 12481;
|
||||
lenBytes[0] = 241 + (length >>> 16);
|
||||
lenBytes[1] = (length >> 8) & 0xff;
|
||||
lenBytes[2] = length & 0xff;
|
||||
return lenBytes.subarray(0, 3);
|
||||
}
|
||||
throw new Error('Overflow error');
|
||||
},
|
||||
writeFieldAndValue(field, _value) {
|
||||
const sink = this.sink;
|
||||
const value = field.associatedType.from(_value);
|
||||
assert(value.toBytesSink, field);
|
||||
sink.put(field.bytes);
|
||||
|
||||
if (field.isVLEncoded) {
|
||||
this.writeLengthEncoded(value);
|
||||
} else {
|
||||
value.toBytesSink(sink);
|
||||
if (field.type === Type.STObject) {
|
||||
sink.put(Field.ObjectEndMarker.bytes);
|
||||
} else if (field.type === Type.STArray) {
|
||||
sink.put(Field.ArrayEndMarker.bytes);
|
||||
}
|
||||
}
|
||||
},
|
||||
writeLengthEncoded(value) {
|
||||
const bytes = new BytesList();
|
||||
value.toBytesSink(bytes);
|
||||
this.put(this.encodeVL(bytes.length));
|
||||
this.writeBytesList(bytes);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
BytesList,
|
||||
BinarySerializer
|
||||
};
|
||||
107
packages/ripple-binary-codec/src/serdes/binary-serializer.ts
Normal file
107
packages/ripple-binary-codec/src/serdes/binary-serializer.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { strict as assert } from 'assert'
|
||||
import { parseBytes, bytesToHex } from '../utils/bytes-utils'
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Enums } from '../enums'
|
||||
|
||||
const BytesSink = {
|
||||
put (/* bytesSequence */) {
|
||||
// any hex string or any object with a `length` and where 0 <= [ix] <= 255
|
||||
}
|
||||
}
|
||||
|
||||
const BytesList = makeClass({
|
||||
implementing: BytesSink,
|
||||
BytesList () {
|
||||
this.arrays = []
|
||||
this.length = 0
|
||||
},
|
||||
put (bytesArg) {
|
||||
const bytes = parseBytes(bytesArg, Uint8Array)
|
||||
this.length += bytes.length
|
||||
this.arrays.push(bytes)
|
||||
return this
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
this.arrays.forEach(arr => {
|
||||
sink.put(arr)
|
||||
})
|
||||
},
|
||||
toBytes () {
|
||||
const concatenated = new Uint8Array(this.length)
|
||||
let pointer = 0
|
||||
this.arrays.forEach(arr => {
|
||||
concatenated.set(arr, pointer)
|
||||
pointer += arr.length
|
||||
})
|
||||
return concatenated
|
||||
},
|
||||
toHex () {
|
||||
return bytesToHex(this.toBytes())
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
const BinarySerializer = makeClass({
|
||||
BinarySerializer (sink) {
|
||||
this.sink = sink
|
||||
},
|
||||
write (value) {
|
||||
value.toBytesSink(this.sink)
|
||||
},
|
||||
put (bytes) {
|
||||
this.sink.put(bytes)
|
||||
},
|
||||
writeType (type, value) {
|
||||
this.write(type.from(value))
|
||||
},
|
||||
writeBytesList (bl) {
|
||||
bl.toBytesSink(this.sink)
|
||||
},
|
||||
encodeVL (len) {
|
||||
let length = len
|
||||
const lenBytes = new Uint8Array(4)
|
||||
if (length <= 192) {
|
||||
lenBytes[0] = length
|
||||
return lenBytes.subarray(0, 1)
|
||||
} else if (length <= 12480) {
|
||||
length -= 193
|
||||
lenBytes[0] = 193 + (length >>> 8)
|
||||
lenBytes[1] = length & 0xff
|
||||
return lenBytes.subarray(0, 2)
|
||||
} else if (length <= 918744) {
|
||||
length -= 12481
|
||||
lenBytes[0] = 241 + (length >>> 16)
|
||||
lenBytes[1] = (length >> 8) & 0xff
|
||||
lenBytes[2] = length & 0xff
|
||||
return lenBytes.subarray(0, 3)
|
||||
}
|
||||
throw new Error('Overflow error')
|
||||
},
|
||||
writeFieldAndValue (field, _value) {
|
||||
const sink = this.sink
|
||||
const value = field.associatedType.from(_value)
|
||||
assert(value.toBytesSink, field)
|
||||
sink.put(field.bytes)
|
||||
|
||||
if (field.isVLEncoded) {
|
||||
this.writeLengthEncoded(value)
|
||||
} else {
|
||||
value.toBytesSink(sink)
|
||||
if (field.type === Enums.Type.STObject) {
|
||||
sink.put(Enums.Field.ObjectEndMarker.bytes)
|
||||
} else if (field.type === Enums.Type.STArray) {
|
||||
sink.put(Enums.Field.ArrayEndMarker.bytes)
|
||||
}
|
||||
}
|
||||
},
|
||||
writeLengthEncoded (value) {
|
||||
const bytes = new BytesList()
|
||||
value.toBytesSink(bytes)
|
||||
this.put(this.encodeVL(bytes.length))
|
||||
this.writeBytesList(bytes)
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
BytesList,
|
||||
BinarySerializer
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
const assert = require('assert');
|
||||
const makeClass = require('./utils/make-class');
|
||||
const {Hash256} = require('./types');
|
||||
const {HashPrefix} = require('./hash-prefixes');
|
||||
const {Sha512Half: Hasher} = require('./hashes');
|
||||
import { strict as assert } from 'assert'
|
||||
import { makeClass } from './utils/make-class';
|
||||
import { coreTypes } from './types';
|
||||
import { HashPrefix } from './hash-prefixes';
|
||||
import { Sha512Half } from './hashes';
|
||||
|
||||
const ShaMapNode = makeClass({
|
||||
virtuals: {
|
||||
@@ -12,12 +12,12 @@ const ShaMapNode = makeClass({
|
||||
},
|
||||
cached: {
|
||||
hash() {
|
||||
const hasher = Hasher.put(this.hashPrefix());
|
||||
const hasher = Sha512Half.put(this.hashPrefix());
|
||||
this.toBytesSink(hasher);
|
||||
return hasher.finish();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, undefined);
|
||||
|
||||
const ShaMapLeaf = makeClass({
|
||||
inherits: ShaMapNode,
|
||||
@@ -39,7 +39,7 @@ const ShaMapLeaf = makeClass({
|
||||
this.item.toBytesSink(sink);
|
||||
this.index.toBytesSink(sink);
|
||||
}
|
||||
});
|
||||
}, undefined);
|
||||
|
||||
const $uper = ShaMapNode.prototype;
|
||||
|
||||
@@ -69,19 +69,19 @@ const ShaMapInner = makeClass({
|
||||
},
|
||||
hash() {
|
||||
if (this.empty()) {
|
||||
return Hash256.ZERO_256;
|
||||
return coreTypes.Hash256.ZERO_256;
|
||||
}
|
||||
return $uper.hash.call(this);
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
for (let i = 0; i < this.branches.length; i++) {
|
||||
const branch = this.branches[i];
|
||||
const hash = branch ? branch.hash() : Hash256.ZERO_256;
|
||||
const hash = branch ? branch.hash() : coreTypes.Hash256.ZERO_256;
|
||||
hash.toBytesSink(sink);
|
||||
}
|
||||
},
|
||||
addItem(index, item, leaf) {
|
||||
assert(index instanceof Hash256);
|
||||
assert(index instanceof coreTypes.Hash256);
|
||||
const nibble = index.nibblet(this.depth);
|
||||
const existing = this.branches[nibble];
|
||||
if (!existing) {
|
||||
@@ -97,12 +97,12 @@ const ShaMapInner = makeClass({
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}, undefined);
|
||||
|
||||
const ShaMap = makeClass({
|
||||
inherits: ShaMapInner
|
||||
});
|
||||
}, undefined);
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
ShaMap
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {decodeAccountID, encodeAccountID} = require('ripple-address-codec');
|
||||
const {Hash160} = require('./hash-160');
|
||||
|
||||
const AccountID = makeClass({
|
||||
AccountID(bytes) {
|
||||
Hash160.call(this, bytes);
|
||||
},
|
||||
inherits: Hash160,
|
||||
statics: {
|
||||
from(value) {
|
||||
return value instanceof this ? value :
|
||||
/^r/.test(value) ? this.fromBase58(value) :
|
||||
new this(value);
|
||||
},
|
||||
cache: {},
|
||||
fromCache(base58) {
|
||||
let cached = this.cache[base58];
|
||||
if (!cached) {
|
||||
cached = this.cache[base58] = this.fromBase58(base58);
|
||||
}
|
||||
return cached;
|
||||
},
|
||||
fromBase58(value) {
|
||||
const acc = new this(decodeAccountID(value));
|
||||
acc._toBase58 = value;
|
||||
return acc;
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
return this.toBase58();
|
||||
},
|
||||
cached: {
|
||||
toBase58() {
|
||||
return encodeAccountID(this._bytes);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
AccountID
|
||||
};
|
||||
42
packages/ripple-binary-codec/src/types/account-id.ts
Normal file
42
packages/ripple-binary-codec/src/types/account-id.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const { decodeAccountID, encodeAccountID } = require('ripple-address-codec')
|
||||
const { Hash160 } = require('./hash-160')
|
||||
|
||||
const AccountID = makeClass({
|
||||
AccountID (bytes) {
|
||||
Hash160.call(this, bytes)
|
||||
},
|
||||
inherits: Hash160,
|
||||
statics: {
|
||||
from (value) {
|
||||
return value instanceof this ? value
|
||||
: /^r/.test(value) ? this.fromBase58(value)
|
||||
: new this(value)
|
||||
},
|
||||
cache: {},
|
||||
fromCache (base58) {
|
||||
let cached = this.cache[base58]
|
||||
if (!cached) {
|
||||
cached = this.cache[base58] = this.fromBase58(base58)
|
||||
}
|
||||
return cached
|
||||
},
|
||||
fromBase58 (value) {
|
||||
const acc = new this(decodeAccountID(value))
|
||||
acc._toBase58 = value
|
||||
return acc
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
return this.toBase58()
|
||||
},
|
||||
cached: {
|
||||
toBase58 () {
|
||||
return encodeAccountID(this._bytes)
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
AccountID
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
const _ = require('lodash');
|
||||
const assert = require('assert');
|
||||
const BN = require('bn.js');
|
||||
const Decimal = require('decimal.js');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {SerializedType} = require('./serialized-type');
|
||||
const {bytesToHex} = require('../utils/bytes-utils');
|
||||
const {Currency} = require('./currency');
|
||||
const {AccountID} = require('./account-id');
|
||||
const {UInt64} = require('./uint-64');
|
||||
|
||||
const MIN_IOU_EXPONENT = -96;
|
||||
const MAX_IOU_EXPONENT = 80;
|
||||
const MAX_IOU_PRECISION = 16;
|
||||
const MIN_IOU_MANTISSA = '1000' + '0000' + '0000' + '0000'; // 16 digits
|
||||
const MAX_IOU_MANTISSA = '9999' + '9999' + '9999' + '9999'; // ..
|
||||
const MAX_IOU = new Decimal(`${MAX_IOU_MANTISSA}e${MAX_IOU_EXPONENT}`);
|
||||
const MIN_IOU = new Decimal(`${MIN_IOU_MANTISSA}e${MIN_IOU_EXPONENT}`);
|
||||
const DROPS_PER_XRP = new Decimal('1e6');
|
||||
const MAX_NETWORK_DROPS = new Decimal('1e17');
|
||||
const MIN_XRP = new Decimal('1e-6')
|
||||
const MAX_XRP = MAX_NETWORK_DROPS.dividedBy(DROPS_PER_XRP);
|
||||
|
||||
// Never use exponential form
|
||||
Decimal.config({
|
||||
toExpPos: MAX_IOU_EXPONENT + MAX_IOU_PRECISION,
|
||||
toExpNeg: MIN_IOU_EXPONENT - MAX_IOU_PRECISION
|
||||
});
|
||||
|
||||
const AMOUNT_PARAMETERS_DESCRIPTION = `
|
||||
Native values must be described in drops, a million of which equal one XRP.
|
||||
This must be an integer number, with the absolute value not exceeding \
|
||||
${MAX_NETWORK_DROPS}
|
||||
|
||||
IOU values must have a maximum precision of ${MAX_IOU_PRECISION} significant \
|
||||
digits. They are serialized as\na canonicalised mantissa and exponent.
|
||||
|
||||
The valid range for a mantissa is between ${MIN_IOU_MANTISSA} and \
|
||||
${MAX_IOU_MANTISSA}
|
||||
The exponent must be >= ${MIN_IOU_EXPONENT} and <= ${MAX_IOU_EXPONENT}
|
||||
|
||||
Thus the largest serializable IOU value is:
|
||||
${MAX_IOU.toString()}
|
||||
|
||||
And the smallest:
|
||||
${MIN_IOU.toString()}
|
||||
`
|
||||
|
||||
function isDefined(val) {
|
||||
return !_.isUndefined(val);
|
||||
}
|
||||
|
||||
function raiseIllegalAmountError(value) {
|
||||
throw new Error(`${value.toString()} is an illegal amount\n` +
|
||||
AMOUNT_PARAMETERS_DESCRIPTION);
|
||||
}
|
||||
|
||||
const parsers = {
|
||||
string(str) {
|
||||
// Using /^\d+$/ here fixes #31
|
||||
if (!str.match(/^\d+$/)) {
|
||||
raiseIllegalAmountError(str);
|
||||
}
|
||||
return [new Decimal(str).dividedBy(DROPS_PER_XRP), Currency.XRP];
|
||||
},
|
||||
object(object) {
|
||||
assert(isDefined(object.currency), 'currency must be defined');
|
||||
assert(isDefined(object.issuer), 'issuer must be defined');
|
||||
return [new Decimal(object.value),
|
||||
Currency.from(object.currency),
|
||||
AccountID.from(object.issuer)];
|
||||
}
|
||||
};
|
||||
|
||||
const Amount = makeClass({
|
||||
Amount(value, currency, issuer, validate = true) {
|
||||
this.value = value || new Decimal('0');
|
||||
this.currency = currency || Currency.XRP;
|
||||
this.issuer = issuer || null;
|
||||
if (validate) {
|
||||
this.assertValueIsValid();
|
||||
}
|
||||
},
|
||||
mixins: SerializedType,
|
||||
statics: {
|
||||
from(value) {
|
||||
if (value instanceof this) {
|
||||
return value;
|
||||
}
|
||||
const parser = parsers[typeof value];
|
||||
if (parser) {
|
||||
return new this(...parser(value));
|
||||
}
|
||||
throw new Error(`unsupported value: ${value}`);
|
||||
},
|
||||
fromParser(parser) {
|
||||
const mantissa = parser.read(8);
|
||||
const b1 = mantissa[0];
|
||||
const b2 = mantissa[1];
|
||||
|
||||
const isIOU = b1 & 0x80;
|
||||
const isPositive = b1 & 0x40;
|
||||
const sign = isPositive ? '' : '-';
|
||||
|
||||
if (isIOU) {
|
||||
mantissa[0] = 0;
|
||||
const currency = parser.readType(Currency);
|
||||
const issuer = parser.readType(AccountID);
|
||||
const exponent = ((b1 & 0x3F) << 2) + ((b2 & 0xff) >> 6) - 97;
|
||||
mantissa[1] &= 0x3F;
|
||||
// decimal.js won't accept e notation with hex
|
||||
const value = new Decimal(`${sign}0x${bytesToHex(mantissa)}`)
|
||||
.times('1e' + exponent);
|
||||
return new this(value, currency, issuer, false);
|
||||
}
|
||||
|
||||
mantissa[0] &= 0x3F;
|
||||
const drops = new Decimal(`${sign}0x${bytesToHex(mantissa)}`);
|
||||
const xrpValue = drops.dividedBy(DROPS_PER_XRP);
|
||||
return new this(xrpValue, Currency.XRP, null, false);
|
||||
}
|
||||
},
|
||||
assertValueIsValid() {
|
||||
// zero is always a valid amount value
|
||||
if (!this.isZero()) {
|
||||
if (this.isNative()) {
|
||||
const abs = this.value.abs();
|
||||
if (abs.lt(MIN_XRP) || abs.gt(MAX_XRP)) {
|
||||
// value is in XRP scale, but show the value in canonical json form
|
||||
raiseIllegalAmountError(this.value.times(DROPS_PER_XRP))
|
||||
}
|
||||
this.verifyNoDecimal(this.value); // This is a secondary fix for #31
|
||||
} else {
|
||||
const p = this.value.precision();
|
||||
const e = this.exponent();
|
||||
if (p > MAX_IOU_PRECISION ||
|
||||
e > MAX_IOU_EXPONENT ||
|
||||
e < MIN_IOU_EXPONENT) {
|
||||
raiseIllegalAmountError(this.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
isNative() {
|
||||
return this.currency.isNative();
|
||||
},
|
||||
mantissa() {
|
||||
// This is a tertiary fix for #31
|
||||
const integerNumberString = this.verifyNoDecimal();
|
||||
|
||||
return new UInt64(
|
||||
new BN(integerNumberString));
|
||||
},
|
||||
verifyNoDecimal() {
|
||||
const integerNumberString = this.value
|
||||
.times('1e' + -this.exponent()).abs().toString();
|
||||
// Ensure that the value (after being multiplied by the exponent)
|
||||
// does not contain a decimal. From the bn.js README:
|
||||
// "decimals are not supported in this library."
|
||||
// eslint-disable-next-line max-len
|
||||
// https://github.com/indutny/bn.js/blob/9cb459f044853b46615464eea1a3ddfc7006463b/README.md
|
||||
if (integerNumberString.indexOf('.') !== -1) {
|
||||
raiseIllegalAmountError(integerNumberString);
|
||||
}
|
||||
return integerNumberString;
|
||||
},
|
||||
isZero() {
|
||||
return this.value.isZero();
|
||||
},
|
||||
exponent() {
|
||||
return this.isNative() ? -6 : this.value.e - 15;
|
||||
},
|
||||
valueString() {
|
||||
return (this.isNative() ? this.value.times(DROPS_PER_XRP) : this.value)
|
||||
.toString();
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
const isNative = this.isNative();
|
||||
const notNegative = !this.value.isNegative();
|
||||
const mantissa = this.mantissa().toBytes();
|
||||
|
||||
if (isNative) {
|
||||
mantissa[0] |= notNegative ? 0x40 : 0;
|
||||
sink.put(mantissa);
|
||||
} else {
|
||||
mantissa[0] |= 0x80;
|
||||
if (!this.isZero()) {
|
||||
if (notNegative) {
|
||||
mantissa[0] |= 0x40;
|
||||
}
|
||||
const exponent = this.value.e - 15;
|
||||
const exponentByte = 97 + exponent;
|
||||
mantissa[0] |= (exponentByte >>> 2);
|
||||
mantissa[1] |= (exponentByte & 0x03) << 6;
|
||||
}
|
||||
sink.put(mantissa);
|
||||
this.currency.toBytesSink(sink);
|
||||
this.issuer.toBytesSink(sink);
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
const valueString = this.valueString();
|
||||
if (this.isNative()) {
|
||||
return valueString;
|
||||
}
|
||||
return {
|
||||
value: valueString,
|
||||
currency: this.currency.toJSON(),
|
||||
issuer: this.issuer.toJSON()
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Amount
|
||||
};
|
||||
216
packages/ripple-binary-codec/src/types/amount.ts
Normal file
216
packages/ripple-binary-codec/src/types/amount.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const _ = require('lodash')
|
||||
const assert = require('assert')
|
||||
const BN = require('bn.js')
|
||||
const Decimal = require('decimal.js')
|
||||
const { SerializedType } = require('./serialized-type')
|
||||
const { bytesToHex } = require('../utils/bytes-utils')
|
||||
const { Currency } = require('./currency')
|
||||
const { AccountID } = require('./account-id')
|
||||
const { UInt64 } = require('./uint-64')
|
||||
|
||||
const MIN_IOU_EXPONENT = -96
|
||||
const MAX_IOU_EXPONENT = 80
|
||||
const MAX_IOU_PRECISION = 16
|
||||
const MIN_IOU_MANTISSA = '1000' + '0000' + '0000' + '0000' // 16 digits
|
||||
const MAX_IOU_MANTISSA = '9999' + '9999' + '9999' + '9999' // ..
|
||||
const MAX_IOU = new Decimal(`${MAX_IOU_MANTISSA}e${MAX_IOU_EXPONENT}`)
|
||||
const MIN_IOU = new Decimal(`${MIN_IOU_MANTISSA}e${MIN_IOU_EXPONENT}`)
|
||||
const DROPS_PER_XRP = new Decimal('1e6')
|
||||
const MAX_NETWORK_DROPS = new Decimal('1e17')
|
||||
const MIN_XRP = new Decimal('1e-6')
|
||||
const MAX_XRP = MAX_NETWORK_DROPS.dividedBy(DROPS_PER_XRP)
|
||||
|
||||
// Never use exponential form
|
||||
Decimal.config({
|
||||
toExpPos: MAX_IOU_EXPONENT + MAX_IOU_PRECISION,
|
||||
toExpNeg: MIN_IOU_EXPONENT - MAX_IOU_PRECISION
|
||||
})
|
||||
|
||||
const AMOUNT_PARAMETERS_DESCRIPTION = `
|
||||
Native values must be described in drops, a million of which equal one XRP.
|
||||
This must be an integer number, with the absolute value not exceeding \
|
||||
${MAX_NETWORK_DROPS}
|
||||
|
||||
IOU values must have a maximum precision of ${MAX_IOU_PRECISION} significant \
|
||||
digits. They are serialized as\na canonicalised mantissa and exponent.
|
||||
|
||||
The valid range for a mantissa is between ${MIN_IOU_MANTISSA} and \
|
||||
${MAX_IOU_MANTISSA}
|
||||
The exponent must be >= ${MIN_IOU_EXPONENT} and <= ${MAX_IOU_EXPONENT}
|
||||
|
||||
Thus the largest serializable IOU value is:
|
||||
${MAX_IOU.toString()}
|
||||
|
||||
And the smallest:
|
||||
${MIN_IOU.toString()}
|
||||
`
|
||||
|
||||
function isDefined (val) {
|
||||
return !_.isUndefined(val)
|
||||
}
|
||||
|
||||
function raiseIllegalAmountError (value) {
|
||||
throw new Error(`${value.toString()} is an illegal amount\n` +
|
||||
AMOUNT_PARAMETERS_DESCRIPTION)
|
||||
}
|
||||
|
||||
const parsers = {
|
||||
string (str) {
|
||||
// Using /^\d+$/ here fixes #31
|
||||
if (!str.match(/^\d+$/)) {
|
||||
raiseIllegalAmountError(str)
|
||||
}
|
||||
return [new Decimal(str).dividedBy(DROPS_PER_XRP), Currency.XRP]
|
||||
},
|
||||
object (object) {
|
||||
assert(isDefined(object.currency), 'currency must be defined')
|
||||
assert(isDefined(object.issuer), 'issuer must be defined')
|
||||
return [new Decimal(object.value),
|
||||
Currency.from(object.currency),
|
||||
AccountID.from(object.issuer)]
|
||||
}
|
||||
}
|
||||
|
||||
const Amount = makeClass({
|
||||
Amount (value, currency, issuer, validate = true) {
|
||||
this.value = value || new Decimal('0')
|
||||
this.currency = currency || Currency.XRP
|
||||
this.issuer = issuer || null
|
||||
if (validate) {
|
||||
this.assertValueIsValid()
|
||||
}
|
||||
},
|
||||
mixins: SerializedType,
|
||||
statics: {
|
||||
from (value) {
|
||||
if (value instanceof this) {
|
||||
return value
|
||||
}
|
||||
const parser = parsers[typeof value]
|
||||
if (parser) {
|
||||
return new this(...parser(value))
|
||||
}
|
||||
throw new Error(`unsupported value: ${value}`)
|
||||
},
|
||||
fromParser (parser) {
|
||||
const mantissa = parser.read(8)
|
||||
const b1 = mantissa[0]
|
||||
const b2 = mantissa[1]
|
||||
|
||||
const isIOU = b1 & 0x80
|
||||
const isPositive = b1 & 0x40
|
||||
const sign = isPositive ? '' : '-'
|
||||
|
||||
if (isIOU) {
|
||||
mantissa[0] = 0
|
||||
const currency = parser.readType(Currency)
|
||||
const issuer = parser.readType(AccountID)
|
||||
const exponent = ((b1 & 0x3F) << 2) + ((b2 & 0xff) >> 6) - 97
|
||||
mantissa[1] &= 0x3F
|
||||
// decimal.js won't accept e notation with hex
|
||||
const value = new Decimal(`${sign}0x${bytesToHex(mantissa)}`)
|
||||
.times('1e' + exponent)
|
||||
return new this(value, currency, issuer, false)
|
||||
}
|
||||
|
||||
mantissa[0] &= 0x3F
|
||||
const drops = new Decimal(`${sign}0x${bytesToHex(mantissa)}`)
|
||||
const xrpValue = drops.dividedBy(DROPS_PER_XRP)
|
||||
return new this(xrpValue, Currency.XRP, null, false)
|
||||
}
|
||||
},
|
||||
assertValueIsValid () {
|
||||
// zero is always a valid amount value
|
||||
if (!this.isZero()) {
|
||||
if (this.isNative()) {
|
||||
const abs = this.value.abs()
|
||||
if (abs.lt(MIN_XRP) || abs.gt(MAX_XRP)) {
|
||||
// value is in XRP scale, but show the value in canonical json form
|
||||
raiseIllegalAmountError(this.value.times(DROPS_PER_XRP))
|
||||
}
|
||||
this.verifyNoDecimal(this.value) // This is a secondary fix for #31
|
||||
} else {
|
||||
const p = this.value.precision()
|
||||
const e = this.exponent()
|
||||
if (p > MAX_IOU_PRECISION ||
|
||||
e > MAX_IOU_EXPONENT ||
|
||||
e < MIN_IOU_EXPONENT) {
|
||||
raiseIllegalAmountError(this.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
isNative () {
|
||||
return this.currency.isNative()
|
||||
},
|
||||
mantissa () {
|
||||
// This is a tertiary fix for #31
|
||||
const integerNumberString = this.verifyNoDecimal()
|
||||
|
||||
return new UInt64(
|
||||
new BN(integerNumberString))
|
||||
},
|
||||
verifyNoDecimal () {
|
||||
const integerNumberString = this.value
|
||||
.times('1e' + -this.exponent()).abs().toString()
|
||||
// Ensure that the value (after being multiplied by the exponent)
|
||||
// does not contain a decimal. From the bn.js README:
|
||||
// "decimals are not supported in this library."
|
||||
// eslint-disable-next-line max-len
|
||||
// https://github.com/indutny/bn.js/blob/9cb459f044853b46615464eea1a3ddfc7006463b/README.md
|
||||
if (integerNumberString.indexOf('.') !== -1) {
|
||||
raiseIllegalAmountError(integerNumberString)
|
||||
}
|
||||
return integerNumberString
|
||||
},
|
||||
isZero () {
|
||||
return this.value.isZero()
|
||||
},
|
||||
exponent () {
|
||||
return this.isNative() ? -6 : this.value.e - 15
|
||||
},
|
||||
valueString () {
|
||||
return (this.isNative() ? this.value.times(DROPS_PER_XRP) : this.value)
|
||||
.toString()
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
const isNative = this.isNative()
|
||||
const notNegative = !this.value.isNegative()
|
||||
const mantissa = this.mantissa().toBytes()
|
||||
|
||||
if (isNative) {
|
||||
mantissa[0] |= notNegative ? 0x40 : 0
|
||||
sink.put(mantissa)
|
||||
} else {
|
||||
mantissa[0] |= 0x80
|
||||
if (!this.isZero()) {
|
||||
if (notNegative) {
|
||||
mantissa[0] |= 0x40
|
||||
}
|
||||
const exponent = this.value.e - 15
|
||||
const exponentByte = 97 + exponent
|
||||
mantissa[0] |= (exponentByte >>> 2)
|
||||
mantissa[1] |= (exponentByte & 0x03) << 6
|
||||
}
|
||||
sink.put(mantissa)
|
||||
this.currency.toBytesSink(sink)
|
||||
this.issuer.toBytesSink(sink)
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
const valueString = this.valueString()
|
||||
if (this.isNative()) {
|
||||
return valueString
|
||||
}
|
||||
return {
|
||||
value: valueString,
|
||||
currency: this.currency.toJSON(),
|
||||
issuer: this.issuer.toJSON()
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Amount
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {parseBytes} = require('../utils/bytes-utils');
|
||||
const {SerializedType} = require('./serialized-type');
|
||||
|
||||
const Blob = makeClass({
|
||||
mixins: SerializedType,
|
||||
Blob(bytes) {
|
||||
if (bytes) {
|
||||
this._bytes = parseBytes(bytes, Uint8Array);
|
||||
} else {
|
||||
this._bytes = new Uint8Array(0);
|
||||
}
|
||||
},
|
||||
statics: {
|
||||
fromParser(parser, hint) {
|
||||
return new this(parser.read(hint));
|
||||
},
|
||||
from(value) {
|
||||
if (value instanceof this) {
|
||||
return value;
|
||||
}
|
||||
return new this(value);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Blob
|
||||
};
|
||||
29
packages/ripple-binary-codec/src/types/blob.ts
Normal file
29
packages/ripple-binary-codec/src/types/blob.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { parseBytes } from '../utils/bytes-utils'
|
||||
import { SerializedType } from './serialized-type'
|
||||
|
||||
const Blob = makeClass({
|
||||
mixins: SerializedType,
|
||||
Blob (bytes) {
|
||||
if (bytes) {
|
||||
this._bytes = parseBytes(bytes, Uint8Array)
|
||||
} else {
|
||||
this._bytes = new Uint8Array(0)
|
||||
}
|
||||
},
|
||||
statics: {
|
||||
fromParser (parser, hint) {
|
||||
return new this(parser.read(hint))
|
||||
},
|
||||
from (value) {
|
||||
if (value instanceof this) {
|
||||
return value
|
||||
}
|
||||
return new this(value)
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Blob
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
const _ = require('lodash');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {slice} = require('../utils/bytes-utils');
|
||||
const {Hash160} = require('./hash-160');
|
||||
const ISO_REGEX = /^[A-Z0-9]{3}$/;
|
||||
const HEX_REGEX = /^[A-F0-9]{40}$/;
|
||||
|
||||
function isoToBytes(iso) {
|
||||
const bytes = new Uint8Array(20);
|
||||
if (iso !== 'XRP') {
|
||||
const isoBytes = iso.split('').map(c => c.charCodeAt(0));
|
||||
bytes.set(isoBytes, 12);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function isISOCode(val) {
|
||||
return val.length === 3; // ISO_REGEX.test(val);
|
||||
}
|
||||
|
||||
function isHex(val) {
|
||||
return HEX_REGEX.test(val);
|
||||
}
|
||||
|
||||
function isStringRepr(val) {
|
||||
return _.isString(val) && (isISOCode(val) || isHex(val));
|
||||
}
|
||||
|
||||
function isBytesArray(val) {
|
||||
return val.length === 20;
|
||||
}
|
||||
|
||||
function isValidRepr(val) {
|
||||
return isStringRepr(val) || isBytesArray(val);
|
||||
}
|
||||
|
||||
function bytesFromRepr(val) {
|
||||
if (isValidRepr(val)) {
|
||||
// We assume at this point that we have an object with a length, either 3,
|
||||
// 20 or 40.
|
||||
return val.length === 3 ? isoToBytes(val) : val;
|
||||
}
|
||||
throw new Error(`Unsupported Currency repr: ${val}`);
|
||||
}
|
||||
|
||||
const $uper = Hash160.prototype;
|
||||
const Currency = makeClass({
|
||||
inherits: Hash160,
|
||||
getters: ['isNative', 'iso'],
|
||||
statics: {
|
||||
init() {
|
||||
this.XRP = new this(new Uint8Array(20));
|
||||
},
|
||||
from(val) {
|
||||
return val instanceof this ? val : new this(bytesFromRepr(val));
|
||||
}
|
||||
},
|
||||
Currency(bytes) {
|
||||
Hash160.call(this, bytes);
|
||||
this.classify();
|
||||
},
|
||||
classify() {
|
||||
// We only have a non null iso() property available if the currency can be
|
||||
// losslessly represented by the 3 letter iso code. If none is available a
|
||||
// hex encoding of the full 20 bytes is the canonical representation.
|
||||
let onlyISO = true;
|
||||
|
||||
const bytes = this._bytes;
|
||||
const code = slice(this._bytes, 12, 15, Array);
|
||||
const iso = code.map(c => String.fromCharCode(c)).join('');
|
||||
|
||||
for (let i = bytes.length - 1; i >= 0; i--) {
|
||||
if (bytes[i] !== 0 && !(i === 12 || i === 13 || i === 14)) {
|
||||
onlyISO = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const lossLessISO = onlyISO && iso !== 'XRP' && ISO_REGEX.test(iso);
|
||||
this._isNative = onlyISO && _.isEqual(code, [0, 0, 0]);
|
||||
this._iso = this._isNative ? 'XRP' : lossLessISO ? iso : null;
|
||||
},
|
||||
toJSON() {
|
||||
if (this.iso()) {
|
||||
return this.iso();
|
||||
}
|
||||
return $uper.toJSON.call(this);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Currency
|
||||
};
|
||||
92
packages/ripple-binary-codec/src/types/currency.ts
Normal file
92
packages/ripple-binary-codec/src/types/currency.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const _ = require('lodash')
|
||||
const { slice } = require('../utils/bytes-utils')
|
||||
const { Hash160 } = require('./hash-160')
|
||||
const ISO_REGEX = /^[A-Z0-9]{3}$/
|
||||
const HEX_REGEX = /^[A-F0-9]{40}$/
|
||||
|
||||
function isoToBytes (iso) {
|
||||
const bytes = new Uint8Array(20)
|
||||
if (iso !== 'XRP') {
|
||||
const isoBytes = iso.split('').map(c => c.charCodeAt(0))
|
||||
bytes.set(isoBytes, 12)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
function isISOCode (val) {
|
||||
return val.length === 3 // ISO_REGEX.test(val);
|
||||
}
|
||||
|
||||
function isHex (val) {
|
||||
return HEX_REGEX.test(val)
|
||||
}
|
||||
|
||||
function isStringRepr (val) {
|
||||
return _.isString(val) && (isISOCode(val) || isHex(val))
|
||||
}
|
||||
|
||||
function isBytesArray (val) {
|
||||
return val.length === 20
|
||||
}
|
||||
|
||||
function isValidRepr (val) {
|
||||
return isStringRepr(val) || isBytesArray(val)
|
||||
}
|
||||
|
||||
function bytesFromRepr (val) {
|
||||
if (isValidRepr(val)) {
|
||||
// We assume at this point that we have an object with a length, either 3,
|
||||
// 20 or 40.
|
||||
return val.length === 3 ? isoToBytes(val) : val
|
||||
}
|
||||
throw new Error(`Unsupported Currency repr: ${val}`)
|
||||
}
|
||||
|
||||
const $uper = Hash160.prototype
|
||||
const Currency = makeClass({
|
||||
inherits: Hash160,
|
||||
getters: ['isNative', 'iso'],
|
||||
statics: {
|
||||
init () {
|
||||
this.XRP = new this(new Uint8Array(20))
|
||||
},
|
||||
from (val) {
|
||||
return val instanceof this ? val : new this(bytesFromRepr(val))
|
||||
}
|
||||
},
|
||||
Currency (bytes) {
|
||||
Hash160.call(this, bytes)
|
||||
this.classify()
|
||||
},
|
||||
classify () {
|
||||
// We only have a non null iso() property available if the currency can be
|
||||
// losslessly represented by the 3 letter iso code. If none is available a
|
||||
// hex encoding of the full 20 bytes is the canonical representation.
|
||||
let onlyISO = true
|
||||
|
||||
const bytes = this._bytes
|
||||
const code = slice(this._bytes, 12, 15, Array)
|
||||
const iso = code.map(c => String.fromCharCode(c)).join('')
|
||||
|
||||
for (let i = bytes.length - 1; i >= 0; i--) {
|
||||
if (bytes[i] !== 0 && !(i === 12 || i === 13 || i === 14)) {
|
||||
onlyISO = false
|
||||
break
|
||||
}
|
||||
}
|
||||
const lossLessISO = onlyISO && iso !== 'XRP' && ISO_REGEX.test(iso)
|
||||
this._isNative = onlyISO && _.isEqual(code, [0, 0, 0])
|
||||
this._iso = this._isNative ? 'XRP' : lossLessISO ? iso : null
|
||||
},
|
||||
toJSON () {
|
||||
if (this.iso()) {
|
||||
return this.iso()
|
||||
}
|
||||
return $uper.toJSON.call(this)
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Currency
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Hash} = require('./hash');
|
||||
|
||||
const Hash128 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: {width: 16}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Hash128
|
||||
};
|
||||
11
packages/ripple-binary-codec/src/types/hash-128.ts
Normal file
11
packages/ripple-binary-codec/src/types/hash-128.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Hash } from './hash'
|
||||
|
||||
const Hash128 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: { width: 16 }
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Hash128
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Hash} = require('./hash');
|
||||
|
||||
const Hash160 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: {width: 20}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Hash160
|
||||
};
|
||||
11
packages/ripple-binary-codec/src/types/hash-160.ts
Normal file
11
packages/ripple-binary-codec/src/types/hash-160.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const { Hash } = require('./hash')
|
||||
|
||||
const Hash160 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: { width: 20 }
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Hash160
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Hash} = require('./hash');
|
||||
|
||||
const Hash256 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: {
|
||||
width: 32,
|
||||
init() {
|
||||
this.ZERO_256 = new this(new Uint8Array(this.width));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Hash256
|
||||
};
|
||||
16
packages/ripple-binary-codec/src/types/hash-256.ts
Normal file
16
packages/ripple-binary-codec/src/types/hash-256.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Hash } from './hash'
|
||||
|
||||
const Hash256 = makeClass({
|
||||
inherits: Hash,
|
||||
statics: {
|
||||
width: 32,
|
||||
init () {
|
||||
this.ZERO_256 = new this(new Uint8Array(this.width))
|
||||
}
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Hash256
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Comparable, SerializedType} = require('./serialized-type');
|
||||
const {compareBytes, parseBytes} = require('../utils/bytes-utils');
|
||||
|
||||
const Hash = makeClass({
|
||||
Hash(bytes) {
|
||||
const width = this.constructor.width;
|
||||
this._bytes = bytes ? parseBytes(bytes, Uint8Array) :
|
||||
new Uint8Array(width);
|
||||
assert.equal(this._bytes.length, width);
|
||||
},
|
||||
mixins: [Comparable, SerializedType],
|
||||
statics: {
|
||||
width: NaN,
|
||||
from(value) {
|
||||
if (value instanceof this) {
|
||||
return value;
|
||||
}
|
||||
return new this(parseBytes(value));
|
||||
},
|
||||
fromParser(parser, hint) {
|
||||
return new this(parser.read(hint || this.width));
|
||||
}
|
||||
},
|
||||
compareTo(other) {
|
||||
return compareBytes(this._bytes, this.constructor.from(other)._bytes);
|
||||
},
|
||||
toString() {
|
||||
return this.toHex();
|
||||
},
|
||||
nibblet(depth) {
|
||||
const byte_ix = depth > 0 ? (depth / 2) | 0 : 0;
|
||||
let b = this._bytes[byte_ix];
|
||||
if (depth % 2 === 0) {
|
||||
b = (b & 0xF0) >>> 4;
|
||||
} else {
|
||||
b = b & 0x0F;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Hash
|
||||
};
|
||||
46
packages/ripple-binary-codec/src/types/hash.ts
Normal file
46
packages/ripple-binary-codec/src/types/hash.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as assert from 'assert'
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Comparable, SerializedType } from './serialized-type'
|
||||
import { compareBytes, parseBytes } from '../utils/bytes-utils'
|
||||
|
||||
const Hash = makeClass({
|
||||
Hash (bytes) {
|
||||
const width = this.constructor.width
|
||||
this._bytes = bytes ? parseBytes(bytes, Uint8Array)
|
||||
: new Uint8Array(width)
|
||||
assert.equal(this._bytes.length, width)
|
||||
},
|
||||
mixins: [Comparable, SerializedType],
|
||||
statics: {
|
||||
width: NaN,
|
||||
from (value) {
|
||||
if (value instanceof this) {
|
||||
return value
|
||||
}
|
||||
return new this(parseBytes(value))
|
||||
},
|
||||
fromParser (parser, hint) {
|
||||
return new this(parser.read(hint || this.width))
|
||||
}
|
||||
},
|
||||
compareTo (other) {
|
||||
return compareBytes(this._bytes, this.constructor.from(other)._bytes)
|
||||
},
|
||||
toString () {
|
||||
return this.toHex()
|
||||
},
|
||||
nibblet (depth) {
|
||||
const byteIx = depth > 0 ? (depth / 2) | 0 : 0
|
||||
let b = this._bytes[byteIx]
|
||||
if (depth % 2 === 0) {
|
||||
b = (b & 0xF0) >>> 4
|
||||
} else {
|
||||
b = b & 0x0F
|
||||
}
|
||||
return b
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Hash
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
const enums = require('../enums');
|
||||
const {Field} = enums;
|
||||
const {AccountID} = require('./account-id');
|
||||
const {Amount} = require('./amount');
|
||||
const {Blob} = require('./blob');
|
||||
const {Currency} = require('./currency');
|
||||
const {Hash128} = require('./hash-128');
|
||||
const {Hash160} = require('./hash-160');
|
||||
const {Hash256} = require('./hash-256');
|
||||
const {PathSet} = require('./path-set');
|
||||
const {STArray} = require('./st-array');
|
||||
const {STObject} = require('./st-object');
|
||||
const {UInt16} = require('./uint-16');
|
||||
const {UInt32} = require('./uint-32');
|
||||
const {UInt64} = require('./uint-64');
|
||||
const {UInt8} = require('./uint-8');
|
||||
const {Vector256} = require('./vector-256');
|
||||
|
||||
const coreTypes = {
|
||||
AccountID,
|
||||
Amount,
|
||||
Blob,
|
||||
Currency,
|
||||
Hash128,
|
||||
Hash160,
|
||||
Hash256,
|
||||
PathSet,
|
||||
STArray,
|
||||
STObject,
|
||||
UInt8,
|
||||
UInt16,
|
||||
UInt32,
|
||||
UInt64,
|
||||
Vector256
|
||||
};
|
||||
|
||||
Field.values.forEach(field => {
|
||||
field.associatedType = coreTypes[field.type];
|
||||
});
|
||||
|
||||
Field.TransactionType.associatedType = enums.TransactionType;
|
||||
Field.TransactionResult.associatedType = enums.TransactionResult;
|
||||
Field.LedgerEntryType.associatedType = enums.LedgerEntryType;
|
||||
|
||||
module.exports = coreTypes;
|
||||
45
packages/ripple-binary-codec/src/types/index.ts
Normal file
45
packages/ripple-binary-codec/src/types/index.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Enums } from '../enums'
|
||||
import { AccountID } from './account-id'
|
||||
import { Amount } from './amount'
|
||||
import { Blob } from './blob'
|
||||
const Field = Enums.Field
|
||||
const { Currency } = require('./currency')
|
||||
const { Hash128 } = require('./hash-128')
|
||||
const { Hash160 } = require('./hash-160')
|
||||
const { Hash256 } = require('./hash-256')
|
||||
const { PathSet } = require('./path-set')
|
||||
const { STArray } = require('./st-array')
|
||||
const { STObject } = require('./st-object')
|
||||
const { UInt16 } = require('./uint-16')
|
||||
const { UInt32 } = require('./uint-32')
|
||||
const { UInt64 } = require('./uint-64')
|
||||
const { UInt8 } = require('./uint-8')
|
||||
const { Vector256 } = require('./vector-256')
|
||||
|
||||
const coreTypes = {
|
||||
AccountID,
|
||||
Amount,
|
||||
Blob,
|
||||
Currency,
|
||||
Hash128,
|
||||
Hash160,
|
||||
Hash256,
|
||||
PathSet,
|
||||
STArray,
|
||||
STObject,
|
||||
UInt8,
|
||||
UInt16,
|
||||
UInt32,
|
||||
UInt64,
|
||||
Vector256
|
||||
}
|
||||
|
||||
Field.values.forEach(field => {
|
||||
field.associatedType = coreTypes[field.type]
|
||||
})
|
||||
|
||||
Field.TransactionType.associatedType = Enums.TransactionType
|
||||
Field.TransactionResult.associatedType = Enums.TransactionResult
|
||||
Field.LedgerEntryType.associatedType = Enums.LedgerEntryType
|
||||
|
||||
export { coreTypes }
|
||||
@@ -1,113 +0,0 @@
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {SerializedType, ensureArrayLikeIs} = require('./serialized-type');
|
||||
const {Currency} = require('./currency');
|
||||
const {AccountID} = require('./account-id');
|
||||
|
||||
const PATHSET_END_BYTE = 0x00;
|
||||
const PATH_SEPARATOR_BYTE = 0xFF;
|
||||
const TYPE_ACCOUNT = 0x01;
|
||||
const TYPE_CURRENCY = 0x10;
|
||||
const TYPE_ISSUER = 0x20;
|
||||
|
||||
const Hop = makeClass({
|
||||
statics: {
|
||||
from(value) {
|
||||
if (value instanceof this) {
|
||||
return value;
|
||||
}
|
||||
const hop = new Hop();
|
||||
value.issuer && (hop.issuer = AccountID.from(value.issuer));
|
||||
value.account && (hop.account = AccountID.from(value.account));
|
||||
value.currency && (hop.currency = Currency.from(value.currency));
|
||||
return hop;
|
||||
},
|
||||
parse(parser, type) {
|
||||
const hop = new Hop();
|
||||
(type & TYPE_ACCOUNT) && (hop.account = AccountID.fromParser(parser));
|
||||
(type & TYPE_CURRENCY) && (hop.currency = Currency.fromParser(parser));
|
||||
(type & TYPE_ISSUER) && (hop.issuer = AccountID.fromParser(parser));
|
||||
return hop;
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
const type = this.type();
|
||||
const ret = {};
|
||||
(type & TYPE_ACCOUNT) && (ret.account = this.account.toJSON());
|
||||
(type & TYPE_ISSUER) && (ret.issuer = this.issuer.toJSON());
|
||||
(type & TYPE_CURRENCY) && (ret.currency = this.currency.toJSON());
|
||||
return ret;
|
||||
},
|
||||
type() {
|
||||
let type = 0;
|
||||
this.issuer && (type += TYPE_ISSUER);
|
||||
this.account && (type += TYPE_ACCOUNT);
|
||||
this.currency && (type += TYPE_CURRENCY);
|
||||
return type;
|
||||
}
|
||||
});
|
||||
|
||||
const Path = makeClass({
|
||||
inherits: Array,
|
||||
statics: {
|
||||
from(value) {
|
||||
return ensureArrayLikeIs(Path, value).withChildren(Hop);
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
return this.map(k => k.toJSON());
|
||||
}
|
||||
});
|
||||
|
||||
const PathSet = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
from(value) {
|
||||
return ensureArrayLikeIs(PathSet, value).withChildren(Path);
|
||||
},
|
||||
fromParser(parser) {
|
||||
const pathSet = new this();
|
||||
let path;
|
||||
while (!parser.end()) {
|
||||
const type = parser.readUInt8();
|
||||
if (type === PATHSET_END_BYTE) {
|
||||
break;
|
||||
}
|
||||
if (type === PATH_SEPARATOR_BYTE) {
|
||||
path = null;
|
||||
continue;
|
||||
}
|
||||
if (!path) {
|
||||
path = new Path();
|
||||
pathSet.push(path);
|
||||
}
|
||||
path.push(Hop.parse(parser, type));
|
||||
}
|
||||
return pathSet;
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
return this.map(k => k.toJSON());
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
let n = 0;
|
||||
this.forEach(path => {
|
||||
if (n++ !== 0) {
|
||||
sink.put([PATH_SEPARATOR_BYTE]);
|
||||
}
|
||||
path.forEach(hop => {
|
||||
sink.put([hop.type()]);
|
||||
hop.account && (hop.account.toBytesSink(sink));
|
||||
hop.currency && (hop.currency.toBytesSink(sink));
|
||||
hop.issuer && (hop.issuer.toBytesSink(sink));
|
||||
});
|
||||
});
|
||||
sink.put([PATHSET_END_BYTE]);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
PathSet
|
||||
};
|
||||
113
packages/ripple-binary-codec/src/types/path-set.ts
Normal file
113
packages/ripple-binary-codec/src/types/path-set.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const { SerializedType, ensureArrayLikeIs } = require('./serialized-type')
|
||||
const { Currency } = require('./currency')
|
||||
const { AccountID } = require('./account-id')
|
||||
|
||||
const PATHSET_END_BYTE = 0x00
|
||||
const PATH_SEPARATOR_BYTE = 0xFF
|
||||
const TYPE_ACCOUNT = 0x01
|
||||
const TYPE_CURRENCY = 0x10
|
||||
const TYPE_ISSUER = 0x20
|
||||
|
||||
const Hop = makeClass({
|
||||
statics: {
|
||||
from (value) {
|
||||
if (value instanceof this) {
|
||||
return value
|
||||
}
|
||||
const hop = new Hop()
|
||||
value.issuer && (hop.issuer = AccountID.from(value.issuer))
|
||||
value.account && (hop.account = AccountID.from(value.account))
|
||||
value.currency && (hop.currency = Currency.from(value.currency))
|
||||
return hop
|
||||
},
|
||||
parse (parser, type) {
|
||||
const hop = new Hop();
|
||||
(type & TYPE_ACCOUNT) && (hop.account = AccountID.fromParser(parser));
|
||||
(type & TYPE_CURRENCY) && (hop.currency = Currency.fromParser(parser));
|
||||
(type & TYPE_ISSUER) && (hop.issuer = AccountID.fromParser(parser))
|
||||
return hop
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
const type = this.type()
|
||||
const ret = <any>{};
|
||||
(type & TYPE_ACCOUNT) && (ret.account = this.account.toJSON());
|
||||
(type & TYPE_ISSUER) && (ret.issuer = this.issuer.toJSON());
|
||||
(type & TYPE_CURRENCY) && (ret.currency = this.currency.toJSON())
|
||||
return ret
|
||||
},
|
||||
type () {
|
||||
let type = 0
|
||||
this.issuer && (type += TYPE_ISSUER)
|
||||
this.account && (type += TYPE_ACCOUNT)
|
||||
this.currency && (type += TYPE_CURRENCY)
|
||||
return type
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
const Path = makeClass({
|
||||
inherits: Array,
|
||||
statics: {
|
||||
from (value) {
|
||||
return ensureArrayLikeIs(Path, value).withChildren(Hop)
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
return this.map(k => k.toJSON())
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
const PathSet = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
from (value) {
|
||||
return ensureArrayLikeIs(PathSet, value).withChildren(Path)
|
||||
},
|
||||
fromParser (parser) {
|
||||
const pathSet = new this()
|
||||
let path
|
||||
while (!parser.end()) {
|
||||
const type = parser.readUInt8()
|
||||
if (type === PATHSET_END_BYTE) {
|
||||
break
|
||||
}
|
||||
if (type === PATH_SEPARATOR_BYTE) {
|
||||
path = null
|
||||
continue
|
||||
}
|
||||
if (!path) {
|
||||
path = new Path()
|
||||
pathSet.push(path)
|
||||
}
|
||||
path.push(Hop.parse(parser, type))
|
||||
}
|
||||
return pathSet
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
return this.map(k => k.toJSON())
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
let n = 0
|
||||
this.forEach(path => {
|
||||
if (n++ !== 0) {
|
||||
sink.put([PATH_SEPARATOR_BYTE])
|
||||
}
|
||||
path.forEach(hop => {
|
||||
sink.put([hop.type()])
|
||||
hop.account && (hop.account.toBytesSink(sink))
|
||||
hop.currency && (hop.currency.toBytesSink(sink))
|
||||
hop.issuer && (hop.issuer.toBytesSink(sink))
|
||||
})
|
||||
})
|
||||
sink.put([PATHSET_END_BYTE])
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
PathSet
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
const {bytesToHex, slice} = require('../utils/bytes-utils');
|
||||
const {BytesList} = require('../serdes/binary-serializer');
|
||||
|
||||
const Comparable = {
|
||||
lt(other) {
|
||||
return this.compareTo(other) < 0;
|
||||
},
|
||||
eq(other) {
|
||||
return this.compareTo(other) === 0;
|
||||
},
|
||||
gt(other) {
|
||||
return this.compareTo(other) > 0;
|
||||
},
|
||||
gte(other) {
|
||||
return this.compareTo(other) > -1;
|
||||
},
|
||||
lte(other) {
|
||||
return this.compareTo(other) < 1;
|
||||
}
|
||||
};
|
||||
|
||||
const SerializedType = {
|
||||
toBytesSink(sink) {
|
||||
sink.put(this._bytes);
|
||||
},
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
},
|
||||
toBytes() {
|
||||
if (this._bytes) {
|
||||
return slice(this._bytes);
|
||||
}
|
||||
const bl = new BytesList();
|
||||
this.toBytesSink(bl);
|
||||
return bl.toBytes();
|
||||
},
|
||||
toJSON() {
|
||||
return this.toHex();
|
||||
},
|
||||
toString() {
|
||||
return this.toHex();
|
||||
}
|
||||
};
|
||||
|
||||
function ensureArrayLikeIs(Type, arrayLike) {
|
||||
return {
|
||||
withChildren(Child) {
|
||||
if (arrayLike instanceof Type) {
|
||||
return arrayLike;
|
||||
}
|
||||
const obj = new Type();
|
||||
for (let i = 0; i < arrayLike.length; i++) {
|
||||
obj.push(Child.from(arrayLike[i]));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ensureArrayLikeIs,
|
||||
SerializedType,
|
||||
Comparable
|
||||
};
|
||||
64
packages/ripple-binary-codec/src/types/serialized-type.ts
Normal file
64
packages/ripple-binary-codec/src/types/serialized-type.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { BytesList } from '../serdes/binary-serializer'
|
||||
const { bytesToHex, slice } = require('../utils/bytes-utils')
|
||||
|
||||
const Comparable = {
|
||||
lt (other) {
|
||||
return this.compareTo(other) < 0
|
||||
},
|
||||
eq (other) {
|
||||
return this.compareTo(other) === 0
|
||||
},
|
||||
gt (other) {
|
||||
return this.compareTo(other) > 0
|
||||
},
|
||||
gte (other) {
|
||||
return this.compareTo(other) > -1
|
||||
},
|
||||
lte (other) {
|
||||
return this.compareTo(other) < 1
|
||||
}
|
||||
}
|
||||
|
||||
const SerializedType = {
|
||||
toBytesSink (sink) {
|
||||
sink.put(this._bytes)
|
||||
},
|
||||
toHex () {
|
||||
return bytesToHex(this.toBytes())
|
||||
},
|
||||
toBytes () {
|
||||
if (this._bytes) {
|
||||
return slice(this._bytes)
|
||||
}
|
||||
const bl = new BytesList()
|
||||
this.toBytesSink(bl)
|
||||
return bl.toBytes()
|
||||
},
|
||||
toJSON () {
|
||||
return this.toHex()
|
||||
},
|
||||
toString () {
|
||||
return this.toHex()
|
||||
}
|
||||
}
|
||||
|
||||
function ensureArrayLikeIs (Type, arrayLike) {
|
||||
return {
|
||||
withChildren (Child) {
|
||||
if (arrayLike instanceof Type) {
|
||||
return arrayLike
|
||||
}
|
||||
const obj = new Type()
|
||||
for (let i = 0; i < arrayLike.length; i++) {
|
||||
obj.push(Child.from(arrayLike[i]))
|
||||
}
|
||||
return obj
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
ensureArrayLikeIs,
|
||||
SerializedType,
|
||||
Comparable
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {ensureArrayLikeIs, SerializedType} = require('./serialized-type');
|
||||
const {Field} = require('../enums');
|
||||
const {STObject} = require('./st-object');
|
||||
const {ArrayEndMarker} = Field;
|
||||
|
||||
const STArray = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
fromParser(parser) {
|
||||
const array = new STArray();
|
||||
while (!parser.end()) {
|
||||
const field = parser.readField();
|
||||
if (field === ArrayEndMarker) {
|
||||
break;
|
||||
}
|
||||
const outer = new STObject();
|
||||
outer[field] = parser.readFieldValue(field);
|
||||
array.push(outer);
|
||||
}
|
||||
return array;
|
||||
},
|
||||
from(value) {
|
||||
return ensureArrayLikeIs(STArray, value).withChildren(STObject);
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
return this.map(v => v.toJSON());
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
this.forEach(so => so.toBytesSink(sink));
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
STArray
|
||||
};
|
||||
38
packages/ripple-binary-codec/src/types/st-array.ts
Normal file
38
packages/ripple-binary-codec/src/types/st-array.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { ensureArrayLikeIs, SerializedType } from './serialized-type'
|
||||
import { Enums } from '../enums'
|
||||
import { STObject } from './st-object'
|
||||
const { ArrayEndMarker } = Enums.Field
|
||||
|
||||
const STArray = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
fromParser (parser) {
|
||||
const array = new STArray()
|
||||
while (!parser.end()) {
|
||||
const field = parser.readField()
|
||||
if (field === ArrayEndMarker) {
|
||||
break
|
||||
}
|
||||
const outer = new STObject()
|
||||
outer[field] = parser.readFieldValue(field)
|
||||
array.push(outer)
|
||||
}
|
||||
return array
|
||||
},
|
||||
from (value) {
|
||||
return ensureArrayLikeIs(STArray, value).withChildren(STObject)
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
return this.map(v => v.toJSON())
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
this.forEach(so => so.toBytesSink(sink))
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
STArray
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
const _ = require('lodash');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Field} = require('../enums');
|
||||
const {BinarySerializer} = require('../serdes/binary-serializer');
|
||||
const {ObjectEndMarker} = Field;
|
||||
const {SerializedType} = require('./serialized-type');
|
||||
|
||||
const STObject = makeClass({
|
||||
mixins: SerializedType,
|
||||
statics: {
|
||||
fromParser(parser, hint) {
|
||||
const end = typeof hint === 'number' ? parser.pos() + hint : null;
|
||||
const so = new this();
|
||||
while (!parser.end(end)) {
|
||||
const field = parser.readField();
|
||||
if (field === ObjectEndMarker) {
|
||||
break;
|
||||
}
|
||||
so[field] = parser.readFieldValue(field);
|
||||
}
|
||||
return so;
|
||||
},
|
||||
from(value) {
|
||||
if (value instanceof this) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
return _.transform(value, (so, val, key) => {
|
||||
const field = Field[key];
|
||||
if (field) {
|
||||
so[field] = field.associatedType.from(val);
|
||||
} else {
|
||||
so[key] = val;
|
||||
}
|
||||
}, new this());
|
||||
}
|
||||
throw new Error(`${value} is unsupported`);
|
||||
}
|
||||
},
|
||||
fieldKeys() {
|
||||
return Object.keys(this).map(k => Field[k]).filter(Boolean);
|
||||
},
|
||||
toJSON() {
|
||||
// Otherwise seemingly result will have same prototype as `this`
|
||||
const accumulator = {}; // of only `own` properties
|
||||
return _.transform(this, (result, value, key) => {
|
||||
result[key] = value && value.toJSON ? value.toJSON() : value;
|
||||
}, accumulator);
|
||||
},
|
||||
toBytesSink(sink, filter = () => true) {
|
||||
const serializer = new BinarySerializer(sink);
|
||||
const fields = this.fieldKeys();
|
||||
const sorted = _.sortBy(fields, 'ordinal');
|
||||
sorted.filter(filter).forEach(field => {
|
||||
const value = this[field];
|
||||
if (!field.isSerialized) {
|
||||
return;
|
||||
}
|
||||
serializer.writeFieldAndValue(field, value);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
STObject
|
||||
};
|
||||
66
packages/ripple-binary-codec/src/types/st-object.ts
Normal file
66
packages/ripple-binary-codec/src/types/st-object.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { Enums } from '../enums'
|
||||
const _ = require('lodash')
|
||||
const { BinarySerializer } = require('../serdes/binary-serializer')
|
||||
const { ObjectEndMarker } = Enums.Field
|
||||
const { SerializedType } = require('./serialized-type')
|
||||
|
||||
const STObject = makeClass({
|
||||
mixins: SerializedType,
|
||||
statics: {
|
||||
fromParser (parser, hint) {
|
||||
const end = typeof hint === 'number' ? parser.pos() + hint : null
|
||||
const so = new this()
|
||||
while (!parser.end(end)) {
|
||||
const field = parser.readField()
|
||||
if (field === ObjectEndMarker) {
|
||||
break
|
||||
}
|
||||
so[field] = parser.readFieldValue(field)
|
||||
}
|
||||
return so
|
||||
},
|
||||
from (value) {
|
||||
if (value instanceof this) {
|
||||
return value
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
return _.transform(value, (so, val, key) => {
|
||||
const field = Enums.Field[key]
|
||||
if (field) {
|
||||
so[field] = field.associatedType.from(val)
|
||||
} else {
|
||||
so[key] = val
|
||||
}
|
||||
}, new this())
|
||||
}
|
||||
throw new Error(`${value} is unsupported`)
|
||||
}
|
||||
},
|
||||
fieldKeys () {
|
||||
return Object.keys(this).map(k => Enums.Field[k]).filter(Boolean)
|
||||
},
|
||||
toJSON () {
|
||||
// Otherwise seemingly result will have same prototype as `this`
|
||||
const accumulator = {} // of only `own` properties
|
||||
return _.transform(this, (result, value, key) => {
|
||||
result[key] = value && value.toJSON ? value.toJSON() : value
|
||||
}, accumulator)
|
||||
},
|
||||
toBytesSink (sink, filter = () => true) {
|
||||
const serializer = new BinarySerializer(sink)
|
||||
const fields = this.fieldKeys()
|
||||
const sorted = _.sortBy(fields, 'ordinal')
|
||||
sorted.filter(filter).forEach(field => {
|
||||
const value = this[field]
|
||||
if (!field.isSerialized) {
|
||||
return
|
||||
}
|
||||
serializer.writeFieldAndValue(field, value)
|
||||
})
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
STObject
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {UInt} = require('./uint');
|
||||
|
||||
const UInt16 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: {width: 2}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
UInt16
|
||||
};
|
||||
11
packages/ripple-binary-codec/src/types/uint-16.ts
Normal file
11
packages/ripple-binary-codec/src/types/uint-16.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { UInt } from './uint'
|
||||
|
||||
const UInt16 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: { width: 2 }
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
UInt16
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {UInt} = require('./uint');
|
||||
|
||||
const UInt32 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: {width: 4}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
UInt32
|
||||
};
|
||||
11
packages/ripple-binary-codec/src/types/uint-32.ts
Normal file
11
packages/ripple-binary-codec/src/types/uint-32.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { UInt } from './uint'
|
||||
|
||||
const UInt32 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: { width: 4 }
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
UInt32
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const BN = require('bn.js');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {bytesToHex, parseBytes, serializeUIntN}
|
||||
= require('../utils/bytes-utils');
|
||||
const {UInt} = require('./uint');
|
||||
|
||||
const HEX_REGEX = /^[A-F0-9]{16}$/;
|
||||
|
||||
const UInt64 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: {width: 8},
|
||||
UInt64(arg = 0) {
|
||||
const argType = typeof arg;
|
||||
if (argType === 'number') {
|
||||
assert(arg >= 0);
|
||||
this._bytes = new Uint8Array(8);
|
||||
this._bytes.set(serializeUIntN(arg, 4), 4);
|
||||
} else if (arg instanceof BN) {
|
||||
this._bytes = parseBytes(arg.toArray('be', 8), Uint8Array);
|
||||
this._toBN = arg;
|
||||
} else {
|
||||
if (argType === 'string') {
|
||||
if (!HEX_REGEX.test(arg)) {
|
||||
throw new Error(`${arg} is not a valid UInt64 hex string`);
|
||||
}
|
||||
}
|
||||
this._bytes = parseBytes(arg, Uint8Array);
|
||||
}
|
||||
assert(this._bytes.length === 8);
|
||||
},
|
||||
toJSON() {
|
||||
return bytesToHex(this._bytes);
|
||||
},
|
||||
valueOf() {
|
||||
return this.toBN();
|
||||
},
|
||||
cached: {
|
||||
toBN() {
|
||||
return new BN(this._bytes);
|
||||
}
|
||||
},
|
||||
toBytes() {
|
||||
return this._bytes;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
UInt64
|
||||
};
|
||||
49
packages/ripple-binary-codec/src/types/uint-64.ts
Normal file
49
packages/ripple-binary-codec/src/types/uint-64.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { strict as assert } from 'assert'
|
||||
import { BN } from 'bn.js'
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { bytesToHex, parseBytes, serializeUIntN } from '../utils/bytes-utils'
|
||||
import { UInt } from './uint'
|
||||
|
||||
const HEX_REGEX = /^[A-F0-9]{16}$/
|
||||
|
||||
const UInt64 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: { width: 8 },
|
||||
UInt64 (arg : any = 0) {
|
||||
const argType = typeof arg
|
||||
if (argType === 'number') {
|
||||
assert(arg >= 0)
|
||||
this._bytes = new Uint8Array(8)
|
||||
this._bytes.set(serializeUIntN(arg, 4), 4)
|
||||
} else if (arg instanceof BN) {
|
||||
this._bytes = parseBytes(arg.toArray('be', 8), Uint8Array)
|
||||
this._toBN = arg
|
||||
} else {
|
||||
if (argType === 'string') {
|
||||
if (!HEX_REGEX.test(arg)) {
|
||||
throw new Error(`${arg} is not a valid UInt64 hex string`)
|
||||
}
|
||||
}
|
||||
this._bytes = parseBytes(arg, Uint8Array)
|
||||
}
|
||||
assert(this._bytes.length === 8)
|
||||
},
|
||||
toJSON () {
|
||||
return bytesToHex(this._bytes)
|
||||
},
|
||||
valueOf () {
|
||||
return this.toBN()
|
||||
},
|
||||
cached: {
|
||||
toBN () {
|
||||
return new BN(this._bytes)
|
||||
}
|
||||
},
|
||||
toBytes () {
|
||||
return this._bytes
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
UInt64
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {UInt} = require('./uint');
|
||||
|
||||
const UInt8 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: {width: 1}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
UInt8
|
||||
};
|
||||
11
packages/ripple-binary-codec/src/types/uint-8.ts
Normal file
11
packages/ripple-binary-codec/src/types/uint-8.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
import { UInt } from './uint'
|
||||
|
||||
const UInt8 = makeClass({
|
||||
inherits: UInt,
|
||||
statics: { width: 1 }
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
UInt8
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const BN = require('bn.js');
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Comparable, SerializedType} = require('./serialized-type');
|
||||
const {serializeUIntN} = require('../utils/bytes-utils');
|
||||
const MAX_VALUES = [0, 255, 65535, 16777215, 4294967295];
|
||||
|
||||
function signum(a, b) {
|
||||
return a < b ? -1 : a === b ? 0 : 1;
|
||||
}
|
||||
|
||||
const UInt = makeClass({
|
||||
mixins: [Comparable, SerializedType],
|
||||
UInt(val = 0) {
|
||||
const max = MAX_VALUES[this.constructor.width];
|
||||
if (val < 0 || !(val <= max)) {
|
||||
throw new Error(`${val} not in range 0 <= $val <= ${max}`);
|
||||
}
|
||||
this.val = val;
|
||||
},
|
||||
statics: {
|
||||
width: 0,
|
||||
fromParser(parser) {
|
||||
const val = this.width > 4 ? parser.read(this.width) :
|
||||
parser.readUIntN(this.width);
|
||||
return new this(val);
|
||||
},
|
||||
from(val) {
|
||||
return val instanceof this ? val : new this(val);
|
||||
}
|
||||
},
|
||||
toJSON() {
|
||||
return this.val;
|
||||
},
|
||||
valueOf() {
|
||||
return this.val;
|
||||
},
|
||||
compareTo(other) {
|
||||
const thisValue = this.valueOf();
|
||||
const otherValue = other.valueOf();
|
||||
if (thisValue instanceof BN) {
|
||||
return otherValue instanceof BN ?
|
||||
thisValue.cmp(otherValue) :
|
||||
thisValue.cmpn(otherValue);
|
||||
} else if (otherValue instanceof BN) {
|
||||
return -other.compareTo(this);
|
||||
}
|
||||
assert(typeof otherValue === 'number');
|
||||
return signum(thisValue, otherValue);
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
sink.put(this.toBytes());
|
||||
},
|
||||
toBytes() {
|
||||
return serializeUIntN(this.val, this.constructor.width);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
UInt
|
||||
};
|
||||
61
packages/ripple-binary-codec/src/types/uint.ts
Normal file
61
packages/ripple-binary-codec/src/types/uint.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { strict as assert } from 'assert'
|
||||
import { BN } from 'bn.js'
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const { Comparable, SerializedType } = require('./serialized-type')
|
||||
const { serializeUIntN } = require('../utils/bytes-utils')
|
||||
const MAX_VALUES = [0, 255, 65535, 16777215, 4294967295]
|
||||
|
||||
function signum (a, b) {
|
||||
return a < b ? -1 : a === b ? 0 : 1
|
||||
}
|
||||
|
||||
const UInt = makeClass({
|
||||
mixins: [Comparable, SerializedType],
|
||||
UInt (val = 0) {
|
||||
const max = MAX_VALUES[this.constructor.width]
|
||||
if (val < 0 || !(val <= max)) {
|
||||
throw new Error(`${val} not in range 0 <= $val <= ${max}`)
|
||||
}
|
||||
this.val = val
|
||||
},
|
||||
statics: {
|
||||
width: 0,
|
||||
fromParser (parser) {
|
||||
const val = this.width > 4 ? parser.read(this.width)
|
||||
: parser.readUIntN(this.width)
|
||||
return new this(val)
|
||||
},
|
||||
from (val) {
|
||||
return val instanceof this ? val : new this(val)
|
||||
}
|
||||
},
|
||||
toJSON () {
|
||||
return this.val
|
||||
},
|
||||
valueOf () {
|
||||
return this.val
|
||||
},
|
||||
compareTo (other) {
|
||||
const thisValue = this.valueOf()
|
||||
const otherValue = other.valueOf()
|
||||
if (thisValue instanceof BN) {
|
||||
return otherValue instanceof BN
|
||||
? thisValue.cmp(otherValue)
|
||||
: thisValue.cmpn(otherValue)
|
||||
} else if (otherValue instanceof BN) {
|
||||
return -other.compareTo(this)
|
||||
}
|
||||
assert(typeof otherValue === 'number')
|
||||
return signum(thisValue, otherValue)
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
sink.put(this.toBytes())
|
||||
},
|
||||
toBytes () {
|
||||
return serializeUIntN(this.val, this.constructor.width)
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
UInt
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
const makeClass = require('../utils/make-class');
|
||||
const {Hash256} = require('./hash-256');
|
||||
const {ensureArrayLikeIs, SerializedType} = require('./serialized-type');
|
||||
|
||||
const Vector256 = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
fromParser(parser, hint) {
|
||||
const vector256 = new this();
|
||||
const bytes = hint !== null ? hint : parser.size() - parser.pos();
|
||||
const hashes = bytes / 32;
|
||||
for (let i = 0; i < hashes; i++) {
|
||||
vector256.push(Hash256.fromParser(parser));
|
||||
}
|
||||
return vector256;
|
||||
},
|
||||
from(value) {
|
||||
return ensureArrayLikeIs(Vector256, value).withChildren(Hash256);
|
||||
}
|
||||
},
|
||||
toBytesSink(sink) {
|
||||
this.forEach(h => h.toBytesSink(sink));
|
||||
},
|
||||
toJSON() {
|
||||
return this.map(hash => hash.toJSON());
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
Vector256
|
||||
};
|
||||
32
packages/ripple-binary-codec/src/types/vector-256.ts
Normal file
32
packages/ripple-binary-codec/src/types/vector-256.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { makeClass } from '../utils/make-class'
|
||||
const { Hash256 } = require('./hash-256')
|
||||
const { ensureArrayLikeIs, SerializedType } = require('./serialized-type')
|
||||
|
||||
const Vector256 = makeClass({
|
||||
mixins: SerializedType,
|
||||
inherits: Array,
|
||||
statics: {
|
||||
fromParser (parser, hint) {
|
||||
const vector256 = new this()
|
||||
const bytes = hint !== null ? hint : parser.size() - parser.pos()
|
||||
const hashes = bytes / 32
|
||||
for (let i = 0; i < hashes; i++) {
|
||||
vector256.push(Hash256.fromParser(parser))
|
||||
}
|
||||
return vector256
|
||||
},
|
||||
from (value) {
|
||||
return ensureArrayLikeIs(Vector256, value).withChildren(Hash256)
|
||||
}
|
||||
},
|
||||
toBytesSink (sink) {
|
||||
this.forEach(h => h.toBytesSink(sink))
|
||||
},
|
||||
toJSON () {
|
||||
return this.map(hash => hash.toJSON())
|
||||
}
|
||||
}, undefined)
|
||||
|
||||
export {
|
||||
Vector256
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
const assert = require('assert');
|
||||
|
||||
function signum(a, b) {
|
||||
return a < b ? -1 : a === b ? 0 : 1;
|
||||
}
|
||||
|
||||
const hexLookup = (function() {
|
||||
const res = {};
|
||||
const reverse = res.reverse = new Array(256);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const char = i.toString(16).toUpperCase();
|
||||
res[char] = i;
|
||||
|
||||
for (let j = 0; j < 16; j++) {
|
||||
const char2 = j.toString(16).toUpperCase();
|
||||
const byte = (i << 4) + j;
|
||||
const byteHex = char + char2;
|
||||
res[byteHex] = byte;
|
||||
reverse[byte] = byteHex;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}());
|
||||
|
||||
const reverseHexLookup = hexLookup.reverse;
|
||||
|
||||
function bytesToHex(sequence) {
|
||||
const buf = Array(sequence.length);
|
||||
for (let i = sequence.length - 1; i >= 0; i--) {
|
||||
buf[i] = reverseHexLookup[sequence[i]];
|
||||
}
|
||||
return buf.join('');
|
||||
}
|
||||
|
||||
function byteForHex(hex) {
|
||||
const byte = hexLookup[hex];
|
||||
if (byte === undefined) {
|
||||
throw new Error(`\`${hex}\` is not a valid hex representation of a byte`);
|
||||
}
|
||||
return byte;
|
||||
}
|
||||
|
||||
function parseBytes(val, Output = Array) {
|
||||
if (!val || val.length === undefined) {
|
||||
throw new Error(`${val} is not a sequence`);
|
||||
}
|
||||
|
||||
if (typeof val === 'string') {
|
||||
const start = val.length % 2;
|
||||
const res = new Output((val.length + start) / 2);
|
||||
for (let i = val.length, to = res.length - 1; to >= start; i -= 2, to--) {
|
||||
res[to] = byteForHex(val.slice(i - 2, i));
|
||||
}
|
||||
if (start === 1) {
|
||||
res[0] = byteForHex(val[0]);
|
||||
}
|
||||
return res;
|
||||
} else if (val instanceof Output) {
|
||||
return val;
|
||||
} else if (Output === Uint8Array) {
|
||||
return new Output(val);
|
||||
}
|
||||
const res = new Output(val.length);
|
||||
for (let i = val.length - 1; i >= 0; i--) {
|
||||
res[i] = val[i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function serializeUIntN(val, width) {
|
||||
const newBytes = new Uint8Array(width);
|
||||
const lastIx = width - 1;
|
||||
for (let i = 0; i < width; i++) {
|
||||
newBytes[lastIx - i] = (val >>> (i * 8) & 0xff);
|
||||
}
|
||||
return newBytes;
|
||||
}
|
||||
|
||||
function compareBytes(a, b) {
|
||||
assert(a.length === b.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const cmp = signum(a[i], b[i]);
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function slice(val, startIx = 0, endIx = val.length, Output = val.constructor) {
|
||||
/* eslint-disable no-param-reassign*/
|
||||
if (startIx < 0) {
|
||||
startIx += val.length;
|
||||
}
|
||||
if (endIx < 0) {
|
||||
endIx += val.length;
|
||||
}
|
||||
/* eslint-enable no-param-reassign*/
|
||||
const len = endIx - startIx;
|
||||
const res = new Output(len);
|
||||
for (let i = endIx - 1; i >= startIx; i--) {
|
||||
res[i - startIx] = val[i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseBytes,
|
||||
bytesToHex,
|
||||
slice,
|
||||
compareBytes,
|
||||
serializeUIntN
|
||||
};
|
||||
113
packages/ripple-binary-codec/src/utils/bytes-utils.ts
Normal file
113
packages/ripple-binary-codec/src/utils/bytes-utils.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { strict as assert } from 'assert'
|
||||
|
||||
function signum (a, b) {
|
||||
return a < b ? -1 : a === b ? 0 : 1
|
||||
}
|
||||
|
||||
const hexLookup = (function () {
|
||||
const res = <any>{}
|
||||
const reverse = res.reverse = new Array(256)
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const char = i.toString(16).toUpperCase()
|
||||
res[char] = i
|
||||
|
||||
for (let j = 0; j < 16; j++) {
|
||||
const char2 = j.toString(16).toUpperCase()
|
||||
const byte = (i << 4) + j
|
||||
const byteHex = char + char2
|
||||
res[byteHex] = byte
|
||||
reverse[byte] = byteHex
|
||||
}
|
||||
}
|
||||
return res
|
||||
}())
|
||||
|
||||
const reverseHexLookup = hexLookup.reverse
|
||||
|
||||
function bytesToHex (sequence) {
|
||||
const buf = Array(sequence.length)
|
||||
for (let i = sequence.length - 1; i >= 0; i--) {
|
||||
buf[i] = reverseHexLookup[sequence[i]]
|
||||
}
|
||||
return buf.join('')
|
||||
}
|
||||
|
||||
function byteForHex (hex) {
|
||||
const byte = hexLookup[hex]
|
||||
if (byte === undefined) {
|
||||
throw new Error(`\`${hex}\` is not a valid hex representation of a byte`)
|
||||
}
|
||||
return byte
|
||||
}
|
||||
|
||||
function parseBytes (val, Output = <any>Array) {
|
||||
if (!val || val.length === undefined) {
|
||||
throw new Error(`${val} is not a sequence`)
|
||||
}
|
||||
|
||||
if (typeof val === 'string') {
|
||||
const start = val.length % 2
|
||||
const res = new Output((val.length + start) / 2)
|
||||
for (let i = val.length, to = res.length - 1; to >= start; i -= 2, to--) {
|
||||
res[to] = byteForHex(val.slice(i - 2, i))
|
||||
}
|
||||
if (start === 1) {
|
||||
res[0] = byteForHex(val[0])
|
||||
}
|
||||
return res
|
||||
} else if (val instanceof Output) {
|
||||
return val
|
||||
} else if (Output === Uint8Array) {
|
||||
return new Output(val)
|
||||
}
|
||||
const res = new Output(val.length)
|
||||
for (let i = val.length - 1; i >= 0; i--) {
|
||||
res[i] = val[i]
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function serializeUIntN (val, width) {
|
||||
const newBytes = new Uint8Array(width)
|
||||
const lastIx = width - 1
|
||||
for (let i = 0; i < width; i++) {
|
||||
newBytes[lastIx - i] = (val >>> (i * 8) & 0xff)
|
||||
}
|
||||
return newBytes
|
||||
}
|
||||
|
||||
function compareBytes (a, b) {
|
||||
assert(a.length === b.length)
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const cmp = signum(a[i], b[i])
|
||||
if (cmp !== 0) {
|
||||
return cmp
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function slice (val, startIx = 0, endIx = val.length, Output = val.constructor) {
|
||||
/* eslint-disable no-param-reassign */
|
||||
if (startIx < 0) {
|
||||
startIx += val.length
|
||||
}
|
||||
if (endIx < 0) {
|
||||
endIx += val.length
|
||||
}
|
||||
/* eslint-enable no-param-reassign */
|
||||
const len = endIx - startIx
|
||||
const res = new Output(len)
|
||||
for (let i = endIx - 1; i >= startIx; i--) {
|
||||
res[i - startIx] = val[i]
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
export {
|
||||
parseBytes,
|
||||
bytesToHex,
|
||||
slice,
|
||||
compareBytes,
|
||||
serializeUIntN
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
const _ = require('lodash');
|
||||
const inherits = require('inherits');
|
||||
|
||||
function forEach(obj, func) {
|
||||
Object.keys(obj || {}).forEach(k => {
|
||||
func(obj[k], k);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureArray(val) {
|
||||
return Array.isArray(val) ? val : [val];
|
||||
}
|
||||
|
||||
module.exports = function makeClass(klass_, definition_) {
|
||||
const definition = definition_ || klass_;
|
||||
let klass = typeof klass_ === 'function' ? klass_ : null;
|
||||
if (klass === null) {
|
||||
for (const k in definition) {
|
||||
if (k[0].match(/[A-Z]/)) {
|
||||
klass = definition[k];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const parent = definition.inherits;
|
||||
if (parent) {
|
||||
if (klass === null) {
|
||||
klass = function() {
|
||||
parent.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
inherits(klass, parent);
|
||||
_.defaults(klass, parent);
|
||||
}
|
||||
if (klass === null) {
|
||||
klass = function() {};
|
||||
}
|
||||
const proto = klass.prototype;
|
||||
function addFunc(original, name, wrapper) {
|
||||
proto[name] = wrapper || original;
|
||||
}
|
||||
(definition.getters || []).forEach(k => {
|
||||
const key = '_' + k;
|
||||
proto[k] = function() {
|
||||
return this[key];
|
||||
};
|
||||
});
|
||||
forEach(definition.virtuals, (f, n) => {
|
||||
addFunc(f, n, function() {
|
||||
throw new Error('unimplemented');
|
||||
});
|
||||
});
|
||||
forEach(definition.methods, addFunc);
|
||||
forEach(definition, (f, n) => {
|
||||
if (_.isFunction(f) && f !== klass) {
|
||||
addFunc(f, n);
|
||||
}
|
||||
});
|
||||
_.assign(klass, definition.statics);
|
||||
if (typeof klass.init === 'function') {
|
||||
klass.init();
|
||||
}
|
||||
forEach(definition.cached, (f, n) => {
|
||||
const key = '_' + n;
|
||||
addFunc(f, n, function() {
|
||||
let value = this[key];
|
||||
if (value === undefined) {
|
||||
value = this[key] = f.call(this);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
});
|
||||
if (definition.mixins) {
|
||||
const mixins = {};
|
||||
// Right-most in the list win
|
||||
ensureArray(definition.mixins).reverse().forEach(o => {
|
||||
_.defaults(mixins, o);
|
||||
});
|
||||
_.defaults(proto, mixins);
|
||||
}
|
||||
|
||||
return klass;
|
||||
};
|
||||
83
packages/ripple-binary-codec/src/utils/make-class.ts
Normal file
83
packages/ripple-binary-codec/src/utils/make-class.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import _ = require('lodash');
|
||||
const inherits = require('inherits')
|
||||
|
||||
function forEach (obj, func) {
|
||||
Object.keys(obj || {}).forEach(k => {
|
||||
func(obj[k], k)
|
||||
})
|
||||
}
|
||||
|
||||
function ensureArray (val) {
|
||||
return Array.isArray(val) ? val : [val]
|
||||
}
|
||||
|
||||
export function makeClass (klass_, definition_) {
|
||||
const definition = definition_ || klass_
|
||||
let klass = typeof klass_ === 'function' ? klass_ : null
|
||||
if (klass === null) {
|
||||
for (const k in definition) {
|
||||
if (k[0].match(/[A-Z]/)) {
|
||||
klass = definition[k]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
const parent = definition.inherits
|
||||
if (parent) {
|
||||
if (klass === null) {
|
||||
klass = function () {
|
||||
parent.apply(this, arguments)
|
||||
}
|
||||
}
|
||||
inherits(klass, parent)
|
||||
_.defaults(klass, parent)
|
||||
}
|
||||
if (klass === null) {
|
||||
klass = function () {}
|
||||
}
|
||||
const proto = klass.prototype
|
||||
function addFunc (original, name, wrapper) {
|
||||
proto[name] = wrapper || original
|
||||
}
|
||||
(definition.getters || []).forEach(k => {
|
||||
const key = '_' + k
|
||||
proto[k] = function () {
|
||||
return this[key]
|
||||
}
|
||||
})
|
||||
forEach(definition.virtuals, (f, n) => {
|
||||
addFunc(f, n, function () {
|
||||
throw new Error('unimplemented')
|
||||
})
|
||||
})
|
||||
forEach(definition.methods, addFunc)
|
||||
forEach(definition, (f, n) => {
|
||||
if (_.isFunction(f) && f !== klass) {
|
||||
addFunc(f, n, undefined)
|
||||
}
|
||||
})
|
||||
_.assign(klass, definition.statics)
|
||||
if (typeof klass.init === 'function') {
|
||||
klass.init()
|
||||
}
|
||||
forEach(definition.cached, (f, n) => {
|
||||
const key = '_' + n
|
||||
addFunc(f, n, function () {
|
||||
let value = this[key]
|
||||
if (value === undefined) {
|
||||
value = this[key] = f.call(this)
|
||||
}
|
||||
return value
|
||||
})
|
||||
})
|
||||
if (definition.mixins) {
|
||||
const mixins = {}
|
||||
// Right-most in the list win
|
||||
ensureArray(definition.mixins).reverse().forEach(o => {
|
||||
_.defaults(mixins, o)
|
||||
})
|
||||
_.defaults(proto, mixins)
|
||||
}
|
||||
|
||||
return klass
|
||||
};
|
||||
Reference in New Issue
Block a user