This commit is contained in:
nitowa
2023-08-15 22:28:03 +02:00
commit 1dae68b1c7
5529 changed files with 1659171 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
Copyright (c) 2015 Ripple Labs Inc.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+107
View File
@@ -0,0 +1,107 @@
# ripple-binary-codec [![NPM](https://img.shields.io/npm/v/ripple-binary-codec.svg)](https://npmjs.org/package/ripple-binary-codec)
Functions to encode/decode to/from the ripple [binary serialization format](https://xrpl.org/serialization.html)
[![NPM](https://nodei.co/npm/ripple-binary-codec.png)](https://www.npmjs.org/package/ripple-binary-codec)
## API
```js
> const api = require('ripple-binary-codec')
```
### decode(binary: string): object
Decode a hex-string into a transaction object.
```js
> api.decode('1100612200000000240000000125000000072D0000000055DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF6240000002540BE4008114D0F5430B66E06498D4CEEC816C7B3337F9982337')
{
LedgerEntryType: 'AccountRoot',
Flags: 0,
Sequence: 1,
PreviousTxnLgrSeq: 7,
OwnerCount: 0,
PreviousTxnID: 'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Balance: '10000000000',
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv'
}
```
### encode(json: object): string
Encode a transaction object into a hex-string. Note that encode filters out fields with undefined values.
```js
> api.encode({
LedgerEntryType: 'AccountRoot',
Flags: 0,
Sequence: 1,
PreviousTxnLgrSeq: 7,
OwnerCount: 0,
PreviousTxnID: 'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Balance: '10000000000',
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv'
})
'1100612200000000240000000125000000072D0000000055DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF6240000002540BE4008114D0F5430B66E06498D4CEEC816C7B3337F9982337'
```
#### X-Address Compatibility
* ripple-binary-codec handles X-addresses by looking for a few specific files (Account/SourceTag, Destination/DestinationTag).
* If other fields (in the future) must to support X-addresses with tags, this library will need to be updated.
* When decoding rippled binary, the output will always output classic address + tag, with no X-addresses. X-address support only applies when encoding to binary.
#### Encoding Currency Codes
* The standard format for currency codes is a three-letter string such as `USD`. This is intended for use with ISO 4217 Currency Codes.
* Currency codes must be exactly 3 ASCII characters in length and there are [a few other rules](https://xrpl.org/currency-formats.html#currency-codes).
* ripple-binary-codec allows any 3-character ASCII string to be encoded as a currency code, although rippled may enforce tighter restrictions.
* When _decoding_, if a currency code is three uppercase letters or numbers (`/^[A-Z0-9]{3}$/`), then it will be decoded into that string. For example,`0000000000000000000000004142430000000000` decodes as `ABC`.
* When decoding, if a currency code is does not match the regex, then it is not considered to be an ISO 4217 or pseudo-ISO currency. ripple-binary-codec will return a 160-bit hex-string (40 hex characters). For example, `0000000000000000000000006142430000000000` (`aBC`) decodes as `0000000000000000000000006142430000000000` because it contains a lowercase letter.
### encodeForSigning(json: object): string
Encode the transaction object for signing.
### encodeForSigningClaim(json: object): string
Encode the transaction object for payment channel claim.
### encodeForMultisigning(json: object, signer: string): string
Encode the transaction object for multi-signing.
### encodeQuality(value: string): string
```js
> api.encodeQuality('195796912.5171664')
'5D06F4C3362FE1D0'
```
### decodeQuality(value: string): string
```js
> api.decodeQuality('5D06F4C3362FE1D0')
'195796912.5171664'
```
### decodeLedgerData(binary: string): object
```js
> api.decodeLedgerData("01E91435016340767BF1C4A3EACEB081770D8ADE216C85445DD6FB002C6B5A2930F2DECE006DA18150CB18F6DD33F6F0990754C962A7CCE62F332FF9C13939B03B864117F0BDA86B6E9B4F873B5C3E520634D343EF5D9D9A4246643D64DAD278BA95DC0EAC6EB5350CF970D521276CDE21276CE60A00")
{
ledger_index: 32052277,
total_coins: '99994494362043555',
parent_hash: 'EACEB081770D8ADE216C85445DD6FB002C6B5A2930F2DECE006DA18150CB18F6',
transaction_hash: 'DD33F6F0990754C962A7CCE62F332FF9C13939B03B864117F0BDA86B6E9B4F87',
account_hash: '3B5C3E520634D343EF5D9D9A4246643D64DAD278BA95DC0EAC6EB5350CF970D5',
parent_close_time: 556231902,
close_time: 556231910,
close_time_resolution: 10,
close_flags: 0
}
```
## Tests
Run unit tests with:
npm test
Use `--coverage` to generate and display code coverage information:
npm test --coverage
This tells jest to output code coverage info in the `./coverage` directory, in addition to showing it on the command line.
+76
View File
@@ -0,0 +1,76 @@
import { BinaryParser } from './serdes/binary-parser';
import { AccountID } from './types/account-id';
import { BinarySerializer, BytesList } from './serdes/binary-serializer';
import { sha512Half, transactionID } from './hashes';
import { JsonObject } from './types/serialized-type';
import { Buffer } from 'buffer/';
/**
* Construct a BinaryParser
*
* @param bytes hex-string to construct BinaryParser from
* @returns A BinaryParser
*/
declare const makeParser: (bytes: string) => BinaryParser;
/**
* Parse BinaryParser into JSON
*
* @param parser BinaryParser object
* @returns JSON for the bytes in the BinaryParser
*/
declare const readJSON: (parser: BinaryParser) => JsonObject;
/**
* Parse a hex-string into its JSON interpretation
*
* @param bytes hex-string to parse into JSON
* @returns JSON
*/
declare const binaryToJSON: (bytes: string) => JsonObject;
/**
* Interface for passing parameters to SerializeObject
*
* @field set signingFieldOnly to true if you want to serialize only signing fields
*/
interface OptionObject {
prefix?: Buffer;
suffix?: Buffer;
signingFieldsOnly?: boolean;
}
/**
* Function to serialize JSON object representing a transaction
*
* @param object JSON object to serialize
* @param opts options for serializing, including optional prefix, suffix, and signingFieldOnly
* @returns A Buffer containing the serialized object
*/
declare function serializeObject(object: JsonObject, opts?: OptionObject): Buffer;
/**
* Serialize an object for signing
*
* @param transaction Transaction to serialize
* @param prefix Prefix bytes to put before the serialized object
* @returns A Buffer with the serialized object
*/
declare function signingData(transaction: JsonObject, prefix?: Buffer): Buffer;
/**
* Interface describing fields required for a Claim
*/
interface ClaimObject extends JsonObject {
channel: string;
amount: string | number;
}
/**
* Serialize a signingClaim
*
* @param claim A claim object to serialize
* @returns the serialized object with appropriate prefix
*/
declare function signingClaimData(claim: ClaimObject): Buffer;
/**
* Serialize a transaction object for multiSigning
*
* @param transaction transaction to serialize
* @param signingAccount Account to sign the transaction with
* @returns serialized transaction with appropriate prefix and suffix
*/
declare function multiSigningData(transaction: JsonObject, signingAccount: string | AccountID): Buffer;
export { BinaryParser, BinarySerializer, BytesList, ClaimObject, makeParser, serializeObject, readJSON, multiSigningData, signingData, signingClaimData, binaryToJSON, sha512Half, transactionID, };
+109
View File
@@ -0,0 +1,109 @@
"use strict";
/* eslint-disable func-style */
Object.defineProperty(exports, "__esModule", { value: true });
exports.transactionID = exports.sha512Half = exports.binaryToJSON = exports.signingClaimData = exports.signingData = exports.multiSigningData = exports.readJSON = exports.serializeObject = exports.makeParser = exports.BytesList = exports.BinarySerializer = exports.BinaryParser = void 0;
const types_1 = require("./types");
const binary_parser_1 = require("./serdes/binary-parser");
Object.defineProperty(exports, "BinaryParser", { enumerable: true, get: function () { return binary_parser_1.BinaryParser; } });
const hash_prefixes_1 = require("./hash-prefixes");
const binary_serializer_1 = require("./serdes/binary-serializer");
Object.defineProperty(exports, "BinarySerializer", { enumerable: true, get: function () { return binary_serializer_1.BinarySerializer; } });
Object.defineProperty(exports, "BytesList", { enumerable: true, get: function () { return binary_serializer_1.BytesList; } });
const hashes_1 = require("./hashes");
Object.defineProperty(exports, "sha512Half", { enumerable: true, get: function () { return hashes_1.sha512Half; } });
Object.defineProperty(exports, "transactionID", { enumerable: true, get: function () { return hashes_1.transactionID; } });
const bigInt = require("big-integer");
/**
* Construct a BinaryParser
*
* @param bytes hex-string to construct BinaryParser from
* @returns A BinaryParser
*/
const makeParser = (bytes) => new binary_parser_1.BinaryParser(bytes);
exports.makeParser = makeParser;
/**
* Parse BinaryParser into JSON
*
* @param parser BinaryParser object
* @returns JSON for the bytes in the BinaryParser
*/
const readJSON = (parser) => parser.readType(types_1.coreTypes.STObject).toJSON();
exports.readJSON = readJSON;
/**
* Parse a hex-string into its JSON interpretation
*
* @param bytes hex-string to parse into JSON
* @returns JSON
*/
const binaryToJSON = (bytes) => readJSON(makeParser(bytes));
exports.binaryToJSON = binaryToJSON;
/**
* Function to serialize JSON object representing a transaction
*
* @param object JSON object to serialize
* @param opts options for serializing, including optional prefix, suffix, and signingFieldOnly
* @returns A Buffer containing the serialized object
*/
function serializeObject(object, opts = {}) {
const { prefix, suffix, signingFieldsOnly = false } = opts;
const bytesList = new binary_serializer_1.BytesList();
if (prefix) {
bytesList.put(prefix);
}
const filter = signingFieldsOnly
? (f) => f.isSigningField
: undefined;
types_1.coreTypes.STObject.from(object, filter).toBytesSink(bytesList);
if (suffix) {
bytesList.put(suffix);
}
return bytesList.toBytes();
}
exports.serializeObject = serializeObject;
/**
* Serialize an object for signing
*
* @param transaction Transaction to serialize
* @param prefix Prefix bytes to put before the serialized object
* @returns A Buffer with the serialized object
*/
function signingData(transaction, prefix = hash_prefixes_1.HashPrefix.transactionSig) {
return serializeObject(transaction, { prefix, signingFieldsOnly: true });
}
exports.signingData = signingData;
/**
* Serialize a signingClaim
*
* @param claim A claim object to serialize
* @returns the serialized object with appropriate prefix
*/
function signingClaimData(claim) {
const num = bigInt(String(claim.amount));
const prefix = hash_prefixes_1.HashPrefix.paymentChannelClaim;
const channel = types_1.coreTypes.Hash256.from(claim.channel).toBytes();
const amount = types_1.coreTypes.UInt64.from(num).toBytes();
const bytesList = new binary_serializer_1.BytesList();
bytesList.put(prefix);
bytesList.put(channel);
bytesList.put(amount);
return bytesList.toBytes();
}
exports.signingClaimData = signingClaimData;
/**
* Serialize a transaction object for multiSigning
*
* @param transaction transaction to serialize
* @param signingAccount Account to sign the transaction with
* @returns serialized transaction with appropriate prefix and suffix
*/
function multiSigningData(transaction, signingAccount) {
const prefix = hash_prefixes_1.HashPrefix.transactionMultiSig;
const suffix = types_1.coreTypes.AccountID.from(signingAccount).toBytes();
return serializeObject(transaction, {
prefix,
suffix,
signingFieldsOnly: true,
});
}
exports.multiSigningData = multiSigningData;
//# sourceMappingURL=binary.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":";AAAA,+BAA+B;;;AAE/B,mCAAmC;AACnC,0DAAqD;AA0InD,6FA1IO,4BAAY,OA0IP;AAxId,mDAA4C;AAC5C,kEAAwE;AAwItE,iGAxIO,oCAAgB,OAwIP;AAChB,0FAzIyB,6BAAS,OAyIzB;AAxIX,qCAAoD;AAiJlD,2FAjJO,mBAAU,OAiJP;AACV,8FAlJmB,sBAAa,OAkJnB;AA7If,sCAAsC;AAEtC;;;;;GAKG;AACH,MAAM,UAAU,GAAG,CAAC,KAAa,EAAgB,EAAE,CAAC,IAAI,4BAAY,CAAC,KAAK,CAAC,CAAA;AA6HzE,gCAAU;AA3HZ;;;;;GAKG;AACH,MAAM,QAAQ,GAAG,CAAC,MAAoB,EAAc,EAAE,CACnD,MAAM,CAAC,QAAQ,CAAC,iBAAS,CAAC,QAAQ,CAAc,CAAC,MAAM,EAAE,CAAA;AAsH1D,4BAAQ;AApHV;;;;;GAKG;AACH,MAAM,YAAY,GAAG,CAAC,KAAa,EAAc,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAA;AAkH7E,oCAAY;AArGd;;;;;;GAMG;AACH,SAAS,eAAe,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EnD,MAAM,SAAS,GAAG,IAAI,6BAAS,EAAE,CAAA;IAEjC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IACrB,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;IACtB,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IACrB,OAAO,SAAS,CAAC,OAAO,EAAE,CAAA;AAC5B,CAAC;AAgCC,4CAAgB;AA9BlB;;;;;;GAMG;AACH,SAAS,gBAAgB,CACvB,WAAuB,EACvB,cAAkC;IAElC,MAAM,MAAM,GAAG,0BAAU,CAAC,mBAAmB,CAAA;IAC7C,MAAM,MAAM,GAAG,iBAAS,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE,CAAA;IACjE,OAAO,eAAe,CAAC,WAAW,EAAE;QAClC,MAAM;QACN,MAAM;QACN,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAA;AACJ,CAAC;AAUC,4CAAgB"}
+9
View File
@@ -0,0 +1,9 @@
import { Field, TransactionType, LedgerEntryType, Type, TransactionResult } from './enums';
import * as types from './types';
import * as binary from './binary';
import { ShaMap } from './shamap';
import * as ledgerHashes from './ledger-hashes';
import * as hashes from './hashes';
import { quality } from './quality';
import { HashPrefix } from './hash-prefixes';
export { hashes, binary, ledgerHashes, Field, TransactionType, LedgerEntryType, Type, TransactionResult, quality, HashPrefix, ShaMap, types, };
+47
View File
@@ -0,0 +1,47 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.types = exports.ShaMap = exports.HashPrefix = exports.quality = exports.TransactionResult = exports.Type = exports.LedgerEntryType = exports.TransactionType = exports.Field = exports.ledgerHashes = exports.binary = exports.hashes = void 0;
const enums_1 = require("./enums");
Object.defineProperty(exports, "Field", { enumerable: true, get: function () { return enums_1.Field; } });
Object.defineProperty(exports, "TransactionType", { enumerable: true, get: function () { return enums_1.TransactionType; } });
Object.defineProperty(exports, "LedgerEntryType", { enumerable: true, get: function () { return enums_1.LedgerEntryType; } });
Object.defineProperty(exports, "Type", { enumerable: true, get: function () { return enums_1.Type; } });
Object.defineProperty(exports, "TransactionResult", { enumerable: true, get: function () { return enums_1.TransactionResult; } });
const types = __importStar(require("./types"));
exports.types = types;
const binary = __importStar(require("./binary"));
exports.binary = binary;
const shamap_1 = require("./shamap");
Object.defineProperty(exports, "ShaMap", { enumerable: true, get: function () { return shamap_1.ShaMap; } });
const ledgerHashes = __importStar(require("./ledger-hashes"));
exports.ledgerHashes = ledgerHashes;
const hashes = __importStar(require("./hashes"));
exports.hashes = hashes;
const quality_1 = require("./quality");
Object.defineProperty(exports, "quality", { enumerable: true, get: function () { return quality_1.quality; } });
const hash_prefixes_1 = require("./hash-prefixes");
Object.defineProperty(exports, "HashPrefix", { enumerable: true, get: function () { return hash_prefixes_1.HashPrefix; } });
//# sourceMappingURL=coretypes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"coretypes.js","sourceRoot":"","sources":["../src/coretypes.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAMgB;AAad,sFAlBA,aAAK,OAkBA;AACL,gGAlBA,uBAAe,OAkBA;AACf,gGAlBA,uBAAe,OAkBA;AACf,qFAlBA,YAAI,OAkBA;AACJ,kGAlBA,yBAAiB,OAkBA;AAhBnB,+CAAgC;AAoB9B,sBAAK;AAnBP,iDAAkC;AAShC,wBAAM;AARR,qCAAiC;AAiB/B,uFAjBO,eAAM,OAiBP;AAhBR,8DAA+C;AAQ7C,oCAAY;AAPd,iDAAkC;AAKhC,wBAAM;AAJR,uCAAmC;AAYjC,wFAZO,iBAAO,OAYP;AAXT,mDAA4C;AAY1C,2FAZO,0BAAU,OAYP"}
+26
View File
@@ -0,0 +1,26 @@
import { BytesList, BinaryParser } from '../binary';
import { Buffer } from 'buffer/';
export declare class Bytes {
readonly name: string;
readonly ordinal: number;
readonly ordinalWidth: number;
readonly bytes: Buffer;
constructor(name: string, ordinal: number, ordinalWidth: number);
toJSON(): string;
toBytesSink(sink: BytesList): void;
toBytes(): Uint8Array;
}
export declare class BytesLookup {
readonly ordinalWidth: number;
constructor(types: Record<string, number>, ordinalWidth: number);
/**
* Add a new name value pair to the BytesLookup.
*
* @param name - A human readable name for the field.
* @param value - The numeric value for the field.
* @throws if the name or value already exist in the lookup because it's unclear how to decode.
*/
add(name: string, value: number): void;
from(value: Bytes | string): Bytes;
fromParser(parser: BinaryParser): Bytes;
}
+64
View File
@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesLookup = exports.Bytes = void 0;
const buffer_1 = require("buffer/");
/*
* @brief: Bytes, name, and ordinal representing one type, ledger_type, transaction type, or result
*/
class Bytes {
constructor(name, ordinal, ordinalWidth) {
this.name = name;
this.ordinal = ordinal;
this.ordinalWidth = ordinalWidth;
this.bytes = buffer_1.Buffer.alloc(ordinalWidth);
for (let i = 0; i < ordinalWidth; i++) {
this.bytes[ordinalWidth - i - 1] = (ordinal >>> (i * 8)) & 0xff;
}
}
toJSON() {
return this.name;
}
toBytesSink(sink) {
sink.put(this.bytes);
}
toBytes() {
return this.bytes;
}
}
exports.Bytes = Bytes;
/*
* @brief: Collection of Bytes objects, mapping bidirectionally
*/
class BytesLookup {
constructor(types, ordinalWidth) {
this.ordinalWidth = ordinalWidth;
Object.entries(types).forEach(([k, v]) => {
this.add(k, v);
});
}
/**
* Add a new name value pair to the BytesLookup.
*
* @param name - A human readable name for the field.
* @param value - The numeric value for the field.
* @throws if the name or value already exist in the lookup because it's unclear how to decode.
*/
add(name, value) {
if (this[name]) {
throw new SyntaxError(`Attempted to add a value with a duplicate name "${name}". This is not allowed because it is unclear how to decode.`);
}
if (this[value.toString()]) {
throw new SyntaxError(`Attempted to add a duplicate value under a different name (Given name: "${name}" and previous name: "${this[value.toString()]}. This is not allowed because it is unclear how to decode.\nGiven value: ${value.toString()}`);
}
this[name] = new Bytes(name, value, this.ordinalWidth);
this[value.toString()] = this[name];
}
from(value) {
return value instanceof Bytes ? value : this[value];
}
fromParser(parser) {
return this.from(parser.readUIntN(this.ordinalWidth).toString());
}
}
exports.BytesLookup = BytesLookup;
//# sourceMappingURL=bytes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../src/enums/bytes.ts"],"names":[],"mappings":";;;AACA,oCAAgC;AAEhC;;GAEG;AACH,MAAa,KAAK;IAGhB,YACW,IAAY,EACZ,OAAe,EACf,YAAoB;QAFpB,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAQ;QACf,iBAAY,GAAZ,YAAY,CAAQ;QAE7B,IAAI,CAAC,KAAK,GAAG,eAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAA;QACvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,EAAE,CAAC,EAAE,EAAE;YACrC,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;SAChE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AC,KAAK,CAAW,CAAA;IAChE,CAAC;IAED,UAAU,CAAC,MAAoB;QAC7B,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;IAClE,CAAC;CACF;AAtCD,kCAsCC"}
+4
View File
@@ -0,0 +1,4 @@
export declare const TYPE_WIDTH = 2;
export declare const LEDGER_ENTRY_WIDTH = 2;
export declare const TRANSACTION_TYPE_WIDTH = 2;
export declare const TRANSACTION_RESULT_WIDTH = 1;
+8
View File
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TRANSACTION_RESULT_WIDTH = exports.TRANSACTION_TYPE_WIDTH = exports.LEDGER_ENTRY_WIDTH = exports.TYPE_WIDTH = void 0;
exports.TYPE_WIDTH = 2;
exports.LEDGER_ENTRY_WIDTH = 2;
exports.TRANSACTION_TYPE_WIDTH = 2;
exports.TRANSACTION_RESULT_WIDTH = 1;
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/enums/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,UAAU,GAAG,CAAC,CAAA;AACd,QAAA,kBAAkB,GAAG,CAAC,CAAA;AACtB,QAAA,sBAAsB,GAAG,CAAC,CAAA;AAC1B,QAAA,wBAAwB,GAAG,CAAC,CAAA"}
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
import { Bytes } from './bytes';
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
/**
* Encoding information for a rippled field, often used in transactions.
* See the enums [README.md](https://github.com/XRPLF/xrpl.js/tree/main/packages/ripple-binary-codec/src/enums) for more details on what each means.
*/
export interface FieldInfo {
nth: number;
isVLEncoded: boolean;
isSerialized: boolean;
isSigningField: boolean;
type: string;
}
export interface FieldInstance {
readonly nth: number;
readonly isVariableLengthEncoded: boolean;
readonly isSerialized: boolean;
readonly isSigningField: boolean;
readonly type: Bytes;
readonly ordinal: number;
readonly name: string;
readonly header: Buffer;
readonly associatedType: typeof SerializedType;
}
export declare class FieldLookup {
constructor(fields: Array<[string, FieldInfo]>, types: Record<string, number>);
fromString(value: string): FieldInstance;
}
+59
View File
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldLookup = void 0;
const bytes_1 = require("./bytes");
const serialized_type_1 = require("../types/serialized-type");
const constants_1 = require("./constants");
const buffer_1 = require("buffer/");
/*
* @brief: Serialize a field based on type_code and Field.nth
*/
function fieldHeader(type, nth) {
const header = [];
if (type < 16) {
if (nth < 16) {
header.push((type << 4) | nth);
}
else {
header.push(type << 4, nth);
}
}
else if (nth < 16) {
header.push(nth, type);
}
else {
header.push(0, type, nth);
}
return buffer_1.Buffer.from(header);
}
function buildField([name, info], typeOrdinal) {
const field = fieldHeader(typeOrdinal, info.nth);
return {
name: name,
nth: info.nth,
isVariableLengthEncoded: info.isVLEncoded,
isSerialized: info.isSerialized,
isSigningField: info.isSigningField,
ordinal: (typeOrdinal << 16) | info.nth,
type: new bytes_1.Bytes(info.type, typeOrdinal, constants_1.TYPE_WIDTH),
header: field,
associatedType: serialized_type_1.SerializedType, // For later assignment in ./types/index.js or Definitions.updateAll(...)
};
}
/*
* @brief: The collection of all fields as defined in definitions.json
*/
class FieldLookup {
constructor(fields, types) {
fields.forEach(([name, field_info]) => {
const typeOrdinal = types[field_info.type];
this[name] = buildField([name, field_info], typeOrdinal);
this[this[name].ordinal.toString()] = this[name];
});
}
fromString(value) {
return this[value];
}
}
exports.FieldLookup = FieldLookup;
//# sourceMappingURL=field.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"field.js","sourceRoot":"","sources":["../../src/enums/field.ts"],"names":[],"mappings":";;;AAAA,mCAA+B;AAC/B,8DAAyD;AACzD,2CAAwC;AACxC,oCAAgC;AA0BhC;;GAEG;AACH,SAAS,WAAW,CA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,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE;YACpC,MAAM,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;YAC1C,IAAI,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,WAAW,CAAC,CAAA;YACxD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAA;QAClD,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,UAAU,CAAC,KAAa;QACtB,OAAO,IAAI,CAAC,KAAK,CAAkB,CAAA;IACrC,CAAC;CACF;AAfD,kCAeC"}
+48
View File
@@ -0,0 +1,48 @@
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
import { BytesList } from '../binary';
export declare const TRANSACTION_TYPES: string[];
export declare class Bytes {
readonly name: string;
readonly ordinal: number;
readonly ordinalWidth: number;
readonly bytes: Buffer;
constructor(name: string, ordinal: number, ordinalWidth: number);
toJSON(): string;
toBytesSink(sink: BytesList): void;
toBytes(): Uint8Array;
}
declare class BytesLookup {
readonly ordinalWidth: number;
constructor(types: Record<string, number>, ordinalWidth: number);
from(value: Bytes | string): Bytes;
fromParser(parser: any): Bytes;
}
interface FieldInfo {
nth: number;
isVLEncoded: boolean;
isSerialized: boolean;
isSigningField: boolean;
type: string;
}
interface FieldInstance {
readonly nth: number;
readonly isVariableLengthEncoded: boolean;
readonly isSerialized: boolean;
readonly isSigningField: boolean;
readonly type: Bytes;
readonly ordinal: number;
readonly name: string;
readonly header: Buffer;
readonly associatedType: typeof SerializedType;
}
declare class FieldLookup {
constructor(fields: Array<[string, FieldInfo]>);
fromString(value: string): FieldInstance;
}
declare const Type: BytesLookup;
declare const LedgerEntryType: BytesLookup;
declare const TransactionType: BytesLookup;
declare const TransactionResult: BytesLookup;
declare const Field: FieldLookup;
export { Field, FieldInstance, Type, LedgerEntryType, TransactionResult, TransactionType, };
+142
View File
@@ -0,0 +1,142 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransactionType = exports.TransactionResult = exports.LedgerEntryType = exports.Type = exports.Field = exports.Bytes = exports.TRANSACTION_TYPES = void 0;
const enums = __importStar(require("./definitions.json"));
const serialized_type_1 = require("../types/serialized-type");
const buffer_1 = require("buffer/");
/*
* @brief: All valid transaction types
*/
exports.TRANSACTION_TYPES = Object.entries(enums.TRANSACTION_TYPES)
.filter(([_key, value]) => value >= 0)
.map(([key, _value]) => key);
const TYPE_WIDTH = 2;
const LEDGER_ENTRY_WIDTH = 2;
const TRANSACTION_TYPE_WIDTH = 2;
const TRANSACTION_RESULT_WIDTH = 1;
/*
* @brief: Serialize a field based on type_code and Field.nth
*/
function fieldHeader(type, nth) {
const header = [];
if (type < 16) {
if (nth < 16) {
header.push((type << 4) | nth);
}
else {
header.push(type << 4, nth);
}
}
else if (nth < 16) {
header.push(nth, type);
}
else {
header.push(0, type, nth);
}
return buffer_1.Buffer.from(header);
}
/*
* @brief: Bytes, name, and ordinal representing one type, ledger_type, transaction type, or result
*/
class Bytes {
constructor(name, ordinal, ordinalWidth) {
this.name = name;
this.ordinal = ordinal;
this.ordinalWidth = ordinalWidth;
this.bytes = buffer_1.Buffer.alloc(ordinalWidth);
for (let i = 0; i < ordinalWidth; i++) {
this.bytes[ordinalWidth - i - 1] = (ordinal >>> (i * 8)) & 0xff;
}
}
toJSON() {
return this.name;
}
toBytesSink(sink) {
sink.put(this.bytes);
}
toBytes() {
return this.bytes;
}
}
exports.Bytes = Bytes;
/*
* @brief: Collection of Bytes objects, mapping bidirectionally
*/
class BytesLookup {
constructor(types, ordinalWidth) {
this.ordinalWidth = ordinalWidth;
Object.entries(types).forEach(([k, v]) => {
this[k] = new Bytes(k, v, ordinalWidth);
this[v.toString()] = this[k];
});
}
from(value) {
return value instanceof Bytes ? value : this[value];
}
fromParser(parser) {
return this.from(parser.readUIntN(this.ordinalWidth).toString());
}
}
function buildField([name, info]) {
const typeOrdinal = enums.TYPES[info.type];
const field = fieldHeader(typeOrdinal, info.nth);
return {
name: name,
nth: info.nth,
isVariableLengthEncoded: info.isVLEncoded,
isSerialized: info.isSerialized,
isSigningField: info.isSigningField,
ordinal: (typeOrdinal << 16) | info.nth,
type: new Bytes(info.type, typeOrdinal, TYPE_WIDTH),
header: field,
associatedType: serialized_type_1.SerializedType, // For later assignment in ./types/index.js
};
}
/*
* @brief: The collection of all fields as defined in definitions.json
*/
class FieldLookup {
constructor(fields) {
fields.forEach(([k, v]) => {
this[k] = buildField([k, v]);
this[this[k].ordinal.toString()] = this[k];
});
}
fromString(value) {
return this[value];
}
}
const Type = new BytesLookup(enums.TYPES, TYPE_WIDTH);
exports.Type = Type;
const LedgerEntryType = new BytesLookup(enums.LEDGER_ENTRY_TYPES, LEDGER_ENTRY_WIDTH);
exports.LedgerEntryType = LedgerEntryType;
const TransactionType = new BytesLookup(enums.TRANSACTION_TYPES, TRANSACTION_TYPE_WIDTH);
exports.TransactionType = TransactionType;
const TransactionResult = new BytesLookup(enums.TRANSACTION_RESULTS, TRANSACTION_RESULT_WIDTH);
exports.TransactionResult = TransactionResult;
const Field = new FieldLookup(enums.FIELDS);
exports.Field = Field;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/enums/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAA2C;AAC3C,8DAAyD;AACzD,oCAAgC;AAGhC;;GAEG;AACU,QAAA,iBAAiB,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,iBAAiB,CAAC;KACrE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC;KACrC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAA;AAE9B,MAAM,UAAU,GAAG,CAAC,CAAA;AACpB,MAAM,kBAAkB,GAAG,CAAC,CAAA;AAC5B,MAAM,sBAAsB,GAAG,CAAC,CAAA;AAChC,MAAM,wBAAwB,GAAG,CAAC,CAAA;AAElC;;GAEG;AACH,SAAS,WAAW,CAAC,IAAY,EAAE,GAAW;IAC5C,MAAM,MAAM,GAAkB,EAAE,CAAA;IAChC,IAAI,IAAI,GAAG,EAAE,EAAE;QACb,IAAI,GAAG,GAAG,EAAE,EAAE;YACZ,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,CAAA;SAC/B;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,EAAE,GAAG,CAAC,CAAA;SAC5B;KACF;SAAM,IAAI,GAAG,GAAG,EAAE,EAAE;QACnB,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;KACvB;SAAM;QACL,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;KAC1B;IACD,OAAO,eA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CAAC,CAAC,CAAA;IACJ,CAAC;IAED,UAAU,CAAC,KAAa;QACtB,OAAO,IAAI,CAAC,KAAK,CAAkB,CAAA;IACrC,CAAC;CACF;AAED,MAAM,IAAI,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;AAkBnD,oBAAI;AAjBN,MAAM,eAAe,GAAG,IAAI,WAAW,CACrC,KAAK,CAAC,kBAAkB,EACxB,kBAAkB,CACnB,CAAA;AAeC,0CAAe;AAdjB,MAAM,eAAe,GAAG,IAAI,WAAW,CACrC,KAAK,CAAC,iBAAiB,EACvB,sBAAsB,CACvB,CAAA;AAaC,0CAAe;AAZjB,MAAM,iBAAiB,GAAG,IAAI,WAAW,CACvC,KAAK,CAAC,mBAAmB,EACzB,wBAAwB,CACzB,CAAA;AAQC,8CAAiB;AAPnB,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,MAAoC,CAAC,CAAA;AAGvE,sBAAK"}
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
/**
* Quick script to re-number values
*/
declare const input: {
temBAD_SEND_XRP_PATHS: number;
temBAD_SEQUENCE: number;
temBAD_SIGNATURE: number;
temBAD_SRC_ACCOUNT: number;
temBAD_TRANSFER_RATE: number;
temDST_IS_SRC: number;
temDST_NEEDED: number;
temINVALID: number;
temINVALID_FLAG: number;
temREDUNDANT: number;
temRIPPLE_EMPTY: number;
temDISABLED: number;
temBAD_SIGNER: number;
temBAD_QUORUM: number;
temBAD_WEIGHT: number;
temBAD_TICK_SIZE: number;
temINVALID_ACCOUNT_ID: number;
temCANNOT_PREAUTH_SELF: number;
temUNCERTAIN: number;
temUNKNOWN: number;
tefFAILURE: number;
tefALREADY: number;
tefBAD_ADD_AUTH: number;
tefBAD_AUTH: number;
tefBAD_LEDGER: number;
tefCREATED: number;
tefEXCEPTION: number;
tefINTERNAL: number;
tefNO_AUTH_REQUIRED: number;
tefPAST_SEQ: number;
tefWRONG_PRIOR: number;
tefMASTER_DISABLED: number;
tefMAX_LEDGER: number;
tefBAD_SIGNATURE: number;
tefBAD_QUORUM: number;
tefNOT_MULTI_SIGNING: number;
tefBAD_AUTH_MASTER: number;
tefINVARIANT_FAILED: number;
tefTOO_BIG: number;
terRETRY: number;
terFUNDS_SPENT: number;
terINSUF_FEE_B: number;
terNO_ACCOUNT: number;
terNO_AUTH: number;
terNO_LINE: number;
terOWNERS: number;
terPRE_SEQ: number;
terLAST: number;
terNO_RIPPLE: number;
terQUEUED: number;
tesSUCCESS: number;
tecCLAIM: number;
tecPATH_PARTIAL: number;
tecUNFUNDED_ADD: number;
tecUNFUNDED_OFFER: number;
tecUNFUNDED_PAYMENT: number;
tecFAILED_PROCESSING: number;
tecDIR_FULL: number;
tecINSUF_RESERVE_LINE: number;
tecINSUF_RESERVE_OFFER: number;
tecNO_DST: number;
tecNO_DST_INSUF_XRP: number;
tecNO_LINE_INSUF_RESERVE: number;
tecNO_LINE_REDUNDANT: number;
tecPATH_DRY: number;
tecUNFUNDED: number;
tecNO_ALTERNATIVE_KEY: number;
tecNO_REGULAR_KEY: number;
tecOWNERS: number;
tecNO_ISSUER: number;
tecNO_AUTH: number;
tecNO_LINE: number;
tecINSUFF_FEE: number;
tecFROZEN: number;
tecNO_TARGET: number;
tecNO_PERMISSION: number;
tecNO_ENTRY: number;
tecINSUFFICIENT_RESERVE: number;
tecNEED_MASTER_KEY: number;
tecDST_TAG_NEEDED: number;
tecINTERNAL: number;
tecOVERSIZE: number;
tecCRYPTOCONDITION_ERROR: number;
tecINVARIANT_FAILED: number;
tecEXPIRED: number;
tecDUPLICATE: number;
tecKILLED: number;
tecHAS_OBLIGATIONS: number;
tecTOO_SOON: number;
};
declare let startingFromTemBADSENDXRPPATHS: number;
declare let startingFromTefFAILURE: number;
declare let startingFromTerRETRY: number;
declare const tesSUCCESS = 0;
declare let startingFromTecCLAIM: number;
declare const startingFromTecDIRFULL = 121;
declare let previousKey: string;
+127
View File
@@ -0,0 +1,127 @@
"use strict";
/**
* 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++},`);
}
});
//# sourceMappingURL=utils-renumber.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils-renumber.js","sourceRoot":"","sources":["../../src/enums/utils-renumber.ts"],"names":[],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AAK,KAAK,EAAE;QACxC,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,MAAM,UAAU,GAAG,CAAC,CAAA;KAC5C;SAAM,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,KAAK,EAAE;QACxC,IAAI,GAAG,KAAK,aAAa,EAAE;YACzB,oBAAoB,GAAG,sBAAsB,CAAA;SAC9C;QACD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,MAAM,oBAAoB,EAAE,GAAG,CAAC,CAAA;KACxD;AACH,CAAC,CAAC,CAAA"}
+44
View File
@@ -0,0 +1,44 @@
import { SerializedType } from '../types/serialized-type';
import { Bytes, BytesLookup } from './bytes';
import { FieldInfo, FieldLookup, FieldInstance } from './field';
interface DefinitionsData {
TYPES: Record<string, number>;
LEDGER_ENTRY_TYPES: Record<string, number>;
FIELDS: (string | FieldInfo)[][];
TRANSACTION_RESULTS: Record<string, number>;
TRANSACTION_TYPES: Record<string, number>;
}
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* XrplDefinitions should be instantiated instead of this class.
*/
declare class XrplDefinitionsBase {
field: FieldLookup;
ledgerEntryType: BytesLookup;
type: BytesLookup;
transactionResult: BytesLookup;
transactionType: BytesLookup;
transactionNames: string[];
dataTypes: Record<string, typeof SerializedType>;
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param types - A list of type objects with the same name as the fields defined.
* You can use the coreTypes object if you are not adding new types.
*/
constructor(enums: DefinitionsData, types: Record<string, typeof SerializedType>);
/**
* Associates each Field to a corresponding class that TypeScript can recognize.
*
* @param types a list of type objects with the same name as the fields defined.
* Defaults to xrpl.js's core type definitions.
*/
associateTypes(types: Record<string, typeof SerializedType>): void;
getAssociatedTypes(): Record<string, typeof SerializedType>;
}
export { DefinitionsData, XrplDefinitionsBase, FieldLookup, FieldInfo, FieldInstance, Bytes, BytesLookup, };
+64
View File
@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesLookup = exports.Bytes = exports.FieldLookup = exports.XrplDefinitionsBase = void 0;
const bytes_1 = require("./bytes");
Object.defineProperty(exports, "Bytes", { enumerable: true, get: function () { return bytes_1.Bytes; } });
Object.defineProperty(exports, "BytesLookup", { enumerable: true, get: function () { return bytes_1.BytesLookup; } });
const field_1 = require("./field");
Object.defineProperty(exports, "FieldLookup", { enumerable: true, get: function () { return field_1.FieldLookup; } });
const constants_1 = require("./constants");
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* XrplDefinitions should be instantiated instead of this class.
*/
class XrplDefinitionsBase {
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param types - A list of type objects with the same name as the fields defined.
* You can use the coreTypes object if you are not adding new types.
*/
constructor(enums, types) {
// Helps catch errors early in JavaScript code.
if (types == undefined) {
throw new TypeError('You passed in an undefined `types` parameter, but `types` must be defined since it contains logic for encoding/decoding transaction data. ' +
'If you have NOT added/modified any data types, you can import and use `coreTypes` from the types folder.');
}
this.type = new bytes_1.BytesLookup(enums.TYPES, constants_1.TYPE_WIDTH);
this.ledgerEntryType = new bytes_1.BytesLookup(enums.LEDGER_ENTRY_TYPES, constants_1.LEDGER_ENTRY_WIDTH);
this.transactionType = new bytes_1.BytesLookup(enums.TRANSACTION_TYPES, constants_1.TRANSACTION_TYPE_WIDTH);
this.transactionResult = new bytes_1.BytesLookup(enums.TRANSACTION_RESULTS, constants_1.TRANSACTION_RESULT_WIDTH);
this.field = new field_1.FieldLookup(enums.FIELDS, enums.TYPES);
this.transactionNames = Object.entries(enums.TRANSACTION_TYPES)
.filter(([_key, value]) => value >= 0)
.map(([key, _value]) => key);
this.dataTypes = {}; // Filled in via associateTypes
this.associateTypes(types);
}
/**
* Associates each Field to a corresponding class that TypeScript can recognize.
*
* @param types a list of type objects with the same name as the fields defined.
* Defaults to xrpl.js's core type definitions.
*/
associateTypes(types) {
// Overwrite any existing type definitions with the given types
this.dataTypes = Object.assign({}, this.dataTypes, types);
Object.values(this.field).forEach((field) => {
field.associatedType = this.dataTypes[field.type.name];
});
this.field['TransactionType'].associatedType = this.transactionType;
this.field['TransactionResult'].associatedType = this.transactionResult;
this.field['LedgerEntryType'].associatedType = this.ledgerEntryType;
}
getAssociatedTypes() {
return this.dataTypes;
}
}
exports.XrplDefinitionsBase = XrplDefinitionsBase;
//# sourceMappingURL=xrpl-definitions-base.js.map
@@ -0,0 +1 @@
{"version":3,"file":"xrpl-definitions-base.js","sourceRoot":"","sources":["../../src/enums/xrpl-definitions-base.ts"],"names":[],"mappings":";;;AACA,mCAA4C;AAmH1C,sFAnHO,aAAK,OAmHP;AACL,4FApHc,mBAAW,OAoHd;AAnHb,mCAA+D;AA+G7D,4FA/GkB,mBAAW,OA+GlB;AA9Gb,2CAKoB;AAUpB;;;GAGG;AACH,MAAM,mBAAmB;IAgBvB;;;;;;;;;;OAUG;IACH,YACE,KAAsB,EACtB,KAA4C;QAE5C,+CAA+C;QAC/C,IAAI,KAAK,IAAI,SAAS,EAAE;YACtB,MAAM,IAAI,SAAS,CACjB,4IAA4I;gBAC1I,0GAA0G,CAC7G,CAAA;SACF;QAED,IAAI,CAAC,IAAI,GAAG,IAAI,mBAAW,CAAC,KAAK,CAAC,KAAK,EAAE,sBAAU,CAAC,CAAA;QACpD,IAAI,CAAC,eAAe,GAAG,IAAI,mBAAW,CACpC,KAAK,CAAC,kBAAkB,EACxB,8BAAkB,CACnB,CAAA;QACD,IAAI,CAAC,eAAe,GAAG,IAAI,mBAAW,CACpC,KAAK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AAC,CAAC,cAAc,GAAG,IAAI,CAAC,eAAe,CAAA;IACrE,CAAC;IAEM,kBAAkB;QACvB,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;CACF;AAIC,kDAAmB"}
+21
View File
@@ -0,0 +1,21 @@
import { type DefinitionsData, XrplDefinitionsBase } from './xrpl-definitions-base';
import { SerializedType } from '../types/serialized-type';
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* Should be used instead of XrplDefinitionsBase since this defines default `types` for serializing/deserializing
* ledger data.
*/
export declare class XrplDefinitions extends XrplDefinitionsBase {
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param types - A list of type objects with the same name as the fields defined.
* You can use the coreTypes object if you are not adding new types.
*/
constructor(enums: DefinitionsData, types?: Record<string, typeof SerializedType>);
}
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.XrplDefinitions = void 0;
const xrpl_definitions_base_1 = require("./xrpl-definitions-base");
const types_1 = require("../types");
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* Should be used instead of XrplDefinitionsBase since this defines default `types` for serializing/deserializing
* ledger data.
*/
class XrplDefinitions extends xrpl_definitions_base_1.XrplDefinitionsBase {
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param types - A list of type objects with the same name as the fields defined.
* You can use the coreTypes object if you are not adding new types.
*/
constructor(enums, types = types_1.coreTypes) {
super(enums, types);
}
}
exports.XrplDefinitions = XrplDefinitions;
//# sourceMappingURL=xrpl-definitions.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"xrpl-definitions.js","sourceRoot":"","sources":["../../src/enums/xrpl-definitions.ts"],"names":[],"mappings":";;;AAAA,mEAGgC;AAChC,oCAAoC;AAGpC;;;;GAIG;AACH,MAAa,eAAgB,SAAQ,2CAAmB;IACtD;;;;;;;;;;OAUG;IACH,YACE,KAAsB,EACtB,QAA+C,iBAAS;QAExD,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IACrB,CAAC;CACF;AAlBD,0CAkBC"}
+6
View File
@@ -0,0 +1,6 @@
import { Buffer } from 'buffer/';
/**
* Maps HashPrefix names to their byte representation
*/
declare const HashPrefix: Record<string, Buffer>;
export { HashPrefix };
+41
View File
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashPrefix = void 0;
const buffer_1 = require("buffer/");
/**
* Write a 32 bit integer to a Buffer
*
* @param uint32 32 bit integer to write to buffer
* @returns a buffer with the bytes representation of uint32
*/
function bytes(uint32) {
const result = buffer_1.Buffer.alloc(4);
result.writeUInt32BE(uint32, 0);
return result;
}
/**
* Maps HashPrefix names to their byte representation
*/
const HashPrefix = {
transactionID: bytes(0x54584e00),
// transaction plus metadata
transaction: bytes(0x534e4400),
// account state
accountStateEntry: bytes(0x4d4c4e00),
// inner node in tree
innerNode: bytes(0x4d494e00),
// ledger master data for signing
ledgerHeader: bytes(0x4c575200),
// inner transaction to sign
transactionSig: bytes(0x53545800),
// inner transaction to sign
transactionMultiSig: bytes(0x534d5400),
// validation for signing
validation: bytes(0x56414c00),
// proposal for signing
proposal: bytes(0x50525000),
// payment channel claim
paymentChannelClaim: bytes(0x434c4d00),
};
exports.HashPrefix = HashPrefix;
//# sourceMappingURL=hash-prefixes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hash-prefixes.js","sourceRoot":"","sources":["../src/hash-prefixes.ts"],"names":[],"mappings":";;;AAAA,oCAAgC;AAEhC;;;;;GAKG;AACH,SAAS,KAAK,CAAC,MAAc;IAC3B,MAAM,MAAM,GAAG,eAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC9B,MAAM,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;IAC/B,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,GAA2B;IACzC,aAAa,EAAE,KAAK,CAAC,UAAU,CAAC;IAChC,4BAA4B;IAC5B,WAAW,EAAE,KAAK,CAAC,UAAU,CAAC;IAC9B,gBAAgB;IAChB,iBAAiB,EAAE,KAAK,CAAC,UAAU,CAAC;IACpC,qBAAqB;IACrB,SAAS,EAAE,KAAK,CAAC,UAAU,CAAC;IAC5B,iCAAiC;IACjC,YAAY,EAAE,KAAK,CAAC,UAAU,CAAC;IAC/B,4BAA4B;IAC5B,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC;IACjC,4BAA4B;IAC5B,mBAAmB,EAAE,KAAK,CAAC,UAAU,CAAC;IACtC,yBAAyB;IACzB,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC;IAC7B,uBAAuB;IACvB,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC;IAC3B,wBAAwB;IACxB,mBAAmB,EAAE,KAAK,CAAC,UAAU,CAAC;CACvC,CAAA;AAEQ,gCAAU"}
+51
View File
@@ -0,0 +1,51 @@
import { Hash256 } from './types/hash-256';
import { BytesList } from './serdes/binary-serializer';
import { Buffer } from 'buffer/';
/**
* Class for hashing with SHA512
* @extends BytesList So SerializedTypes can write bytes to a Sha512Half
*/
declare class Sha512Half extends BytesList {
private hash;
/**
* Construct a new Sha512Hash and write bytes this.hash
*
* @param bytes bytes to write to this.hash
* @returns the new Sha512Hash object
*/
static put(bytes: Buffer): Sha512Half;
/**
* Write bytes to an existing Sha512Hash
*
* @param bytes bytes to write to object
* @returns the Sha512 object
*/
put(bytes: Buffer): Sha512Half;
/**
* Compute SHA512 hash and slice in half
*
* @returns half of a SHA512 hash
*/
finish256(): Buffer;
/**
* Constructs a Hash256 from the Sha512Half object
*
* @returns a Hash256 object
*/
finish(): Hash256;
}
/**
* compute SHA512 hash of a list of bytes
*
* @param args zero or more arguments to hash
* @returns the sha512half hash of the arguments.
*/
declare function sha512Half(...args: Buffer[]): Buffer;
/**
* Construct a transactionID from a Serialized Transaction
*
* @param serialized bytes to hash
* @returns a Hash256 object
*/
declare function transactionID(serialized: Buffer): Hash256;
export { Sha512Half, sha512Half, transactionID };
+77
View File
@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transactionID = exports.sha512Half = exports.Sha512Half = void 0;
const hash_prefixes_1 = require("./hash-prefixes");
const createHash = require("create-hash");
const hash_256_1 = require("./types/hash-256");
const binary_serializer_1 = require("./serdes/binary-serializer");
const buffer_1 = require("buffer/");
/**
* Class for hashing with SHA512
* @extends BytesList So SerializedTypes can write bytes to a Sha512Half
*/
class Sha512Half extends binary_serializer_1.BytesList {
constructor() {
super(...arguments);
this.hash = createHash('sha512');
}
/**
* Construct a new Sha512Hash and write bytes this.hash
*
* @param bytes bytes to write to this.hash
* @returns the new Sha512Hash object
*/
static put(bytes) {
return new Sha512Half().put(bytes);
}
/**
* Write bytes to an existing Sha512Hash
*
* @param bytes bytes to write to object
* @returns the Sha512 object
*/
put(bytes) {
this.hash.update(bytes);
return this;
}
/**
* Compute SHA512 hash and slice in half
*
* @returns half of a SHA512 hash
*/
finish256() {
return buffer_1.Buffer.from(this.hash.digest().slice(0, 32));
}
/**
* Constructs a Hash256 from the Sha512Half object
*
* @returns a Hash256 object
*/
finish() {
return new hash_256_1.Hash256(this.finish256());
}
}
exports.Sha512Half = Sha512Half;
/**
* compute SHA512 hash of a list of bytes
*
* @param args zero or more arguments to hash
* @returns the sha512half hash of the arguments.
*/
function sha512Half(...args) {
const hash = new Sha512Half();
args.forEach((a) => hash.put(a));
return hash.finish256();
}
exports.sha512Half = sha512Half;
/**
* Construct a transactionID from a Serialized Transaction
*
* @param serialized bytes to hash
* @returns a Hash256 object
*/
function transactionID(serialized) {
return new hash_256_1.Hash256(sha512Half(hash_prefixes_1.HashPrefix.transactionID, serialized));
}
exports.transactionID = transactionID;
//# sourceMappingURL=hashes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hashes.js","sourceRoot":"","sources":["../src/hashes.ts"],"names":[],"mappings":";;;AAAA,mDAA4C;AAC5C,0CAA0C;AAC1C,+CAA0C;AAC1C,kEAAsD;AACtD,oCAAgC;AAEhC;;;GAGG;AACH,MAAM,UAAW,SAAQ,6BAAS;IAAlC;;QACU,SAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAA;IAwCrC,CAAC;IAtCC;;;;;OAKG;IACH,MAAM,CAAC,GAAG,CAAC,KAAa;QACtB,OAAO,IAAI,UAAU,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;IACpC,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,KAAa;QACf,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QACvB,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;OAIG;IACH,SAAS;QACP,OAAO,eAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,IAAI,kBAAO,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;IACtC,CAAC;CACF;AAwBQ,gCAAU;AAtBnB;;;;;GAKG;AACH,SAAS,UAAU,CAAC,GAAG,IAAc;IACnC,MAAM,IAAI,GAAG,IAAI,UAAU,EAAE,CAAA;IAC7B,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;IAChC,OAAO,IAAI,CAAC,SAAS,EAAE,CAAA;AACzB,CAAC;AAYoB,gCAAU;AAV/B;;;;;GAKG;AACH,SAAS,aAAa,CAAC,UAAkB;IACvC,OAAO,IAAI,kBAAO,CAAC,UAAU,CAAC,0BAAU,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC,CAAA;AACtE,CAAC;AAEgC,sCAAa"}
+56
View File
@@ -0,0 +1,56 @@
import { decodeLedgerData } from './ledger-hashes';
import { JsonObject } from './types/serialized-type';
import { TRANSACTION_TYPES } from './enums';
/**
* Decode a transaction
*
* @param binary hex-string of the encoded transaction
* @returns the JSON representation of the transaction
*/
declare function decode(binary: string): JsonObject;
/**
* Encode a transaction
*
* @param json The JSON representation of a transaction
* @returns A hex-string of the encoded transaction
*/
declare function encode(json: object): string;
/**
* Encode a transaction and prepare for signing
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
declare function encodeForSigning(json: object): string;
/**
* Encode a transaction and prepare for signing with a claim
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
declare function encodeForSigningClaim(json: object): string;
/**
* Encode a transaction and prepare for multi-signing
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
declare function encodeForMultisigning(json: object, signer: string): string;
/**
* Encode a quality value
*
* @param value string representation of a number
* @returns a hex-string representing the quality
*/
declare function encodeQuality(value: string): string;
/**
* Decode a quality value
*
* @param value hex-string of a quality
* @returns a string representing the quality
*/
declare function decodeQuality(value: string): string;
export { decode, encode, encodeForSigning, encodeForSigningClaim, encodeForMultisigning, encodeQuality, decodeQuality, decodeLedgerData, TRANSACTION_TYPES, };
+123
View File
@@ -0,0 +1,123 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TRANSACTION_TYPES = exports.decodeLedgerData = exports.decodeQuality = exports.encodeQuality = exports.encodeForMultisigning = exports.encodeForSigningClaim = exports.encodeForSigning = exports.encode = exports.decode = void 0;
const assert = __importStar(require("assert"));
const coretypes_1 = require("./coretypes");
const ledger_hashes_1 = require("./ledger-hashes");
Object.defineProperty(exports, "decodeLedgerData", { enumerable: true, get: function () { return ledger_hashes_1.decodeLedgerData; } });
const enums_1 = require("./enums");
Object.defineProperty(exports, "TRANSACTION_TYPES", { enumerable: true, get: function () { return enums_1.TRANSACTION_TYPES; } });
const { signingData, signingClaimData, multiSigningData, binaryToJSON, serializeObject, } = coretypes_1.binary;
/**
* Decode a transaction
*
* @param binary hex-string of the encoded transaction
* @returns the JSON representation of the transaction
*/
function decode(binary) {
assert.ok(typeof binary === 'string', 'binary must be a hex string');
return binaryToJSON(binary);
}
exports.decode = decode;
/**
* Encode a transaction
*
* @param json The JSON representation of a transaction
* @returns A hex-string of the encoded transaction
*/
function encode(json) {
assert.ok(typeof json === 'object');
return serializeObject(json)
.toString('hex')
.toUpperCase();
}
exports.encode = encode;
/**
* Encode a transaction and prepare for signing
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
function encodeForSigning(json) {
assert.ok(typeof json === 'object');
return signingData(json)
.toString('hex')
.toUpperCase();
}
exports.encodeForSigning = encodeForSigning;
/**
* Encode a transaction and prepare for signing with a claim
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
function encodeForSigningClaim(json) {
assert.ok(typeof json === 'object');
return signingClaimData(json)
.toString('hex')
.toUpperCase();
}
exports.encodeForSigningClaim = encodeForSigningClaim;
/**
* Encode a transaction and prepare for multi-signing
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @returns a hex string of the encoded transaction
*/
function encodeForMultisigning(json, signer) {
assert.ok(typeof json === 'object');
assert.equal(json['SigningPubKey'], '');
return multiSigningData(json, signer)
.toString('hex')
.toUpperCase();
}
exports.encodeForMultisigning = encodeForMultisigning;
/**
* Encode a quality value
*
* @param value string representation of a number
* @returns a hex-string representing the quality
*/
function encodeQuality(value) {
assert.ok(typeof value === 'string');
return coretypes_1.quality.encode(value).toString('hex').toUpperCase();
}
exports.encodeQuality = encodeQuality;
/**
* Decode a quality value
*
* @param value hex-string of a quality
* @returns a string representing the quality
*/
function decodeQuality(value) {
assert.ok(typeof value === 'string');
return coretypes_1.quality.decode(value).toString();
}
exports.decodeQuality = decodeQuality;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAChC,2CAA6C;AAC7C,mDAAkD;AA8GhD,iGA9GO,gCAAgB,OA8GP;AA3GlB,mCAA2C;AA4GzC,kGA5GO,yBAAiB,OA4GP;AA1GnB,MAAM,EACJ,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,eAAe,GAChB,GAAG,kBAAM,CAAA;AAEV;;;;;GAKG;AACH,SAAS,MAAM,CAAC,MAAc;IAC5B,MAAM,CAAC,EAAE,CAAC,OAAO,MAAM,KAAK,QAAQ,EAAE,6BAA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K,QAAQ,CAAC,CAAA;IACpC,OAAO,mBAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,CAAA;AAC5D,CAAC;AAmBC,sCAAa;AAjBf;;;;;GAKG;AACH,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,CAAC,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAA;IACpC,OAAO,mBAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAA;AACzC,CAAC;AASC,sCAAa"}
+46
View File
@@ -0,0 +1,46 @@
import { Hash256 } from './types/hash-256';
import { JsonObject } from './types/serialized-type';
import bigInt = require('big-integer');
/**
* Function computing the hash of a transaction tree
*
* @param param An array of transaction objects to hash
* @returns A Hash256 object
*/
declare function transactionTreeHash(param: Array<JsonObject>): Hash256;
/**
* Function computing the hash of accountState
*
* @param param A list of accountStates hash
* @returns A Hash256 object
*/
declare function accountStateHash(param: Array<JsonObject>): Hash256;
/**
* Interface describing a ledger header
*/
interface ledgerObject {
ledger_index: number;
total_coins: string | number | bigInt.BigInteger;
parent_hash: string;
transaction_hash: string;
account_hash: string;
parent_close_time: number;
close_time: number;
close_time_resolution: number;
close_flags: number;
}
/**
* Serialize and hash a ledger header
*
* @param header a ledger header
* @returns the hash of header
*/
declare function ledgerHash(header: ledgerObject): Hash256;
/**
* Decodes a serialized ledger header
*
* @param binary A serialized ledger header
* @returns A JSON object describing a ledger header
*/
declare function decodeLedgerData(binary: string): object;
export { accountStateHash, transactionTreeHash, ledgerHash, decodeLedgerData };
+158
View File
@@ -0,0 +1,158 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeLedgerData = exports.ledgerHash = exports.transactionTreeHash = exports.accountStateHash = void 0;
const assert = __importStar(require("assert"));
const shamap_1 = require("./shamap");
const hash_prefixes_1 = require("./hash-prefixes");
const hashes_1 = require("./hashes");
const binary_1 = require("./binary");
const hash_256_1 = require("./types/hash-256");
const st_object_1 = require("./types/st-object");
const uint_64_1 = require("./types/uint-64");
const uint_32_1 = require("./types/uint-32");
const uint_8_1 = require("./types/uint-8");
const binary_parser_1 = require("./serdes/binary-parser");
const bigInt = require("big-integer");
/**
* Computes the hash of a list of objects
*
* @param itemizer Converts an item into a format that can be added to SHAMap
* @param itemsJson Array of items to add to a SHAMap
* @returns the hash of the SHAMap
*/
function computeHash(itemizer, itemsJson) {
const map = new shamap_1.ShaMap();
itemsJson.forEach((item) => map.addItem(...itemizer(item)));
return map.hash();
}
/**
* Convert a transaction into an index and an item
*
* @param json transaction with metadata
* @returns a tuple of index and item to be added to SHAMap
*/
function transactionItemizer(json) {
assert.ok(json.hash);
const index = hash_256_1.Hash256.from(json.hash);
const item = {
hashPrefix() {
return hash_prefixes_1.HashPrefix.transaction;
},
toBytesSink(sink) {
const serializer = new binary_1.BinarySerializer(sink);
serializer.writeLengthEncoded(st_object_1.STObject.from(json));
serializer.writeLengthEncoded(st_object_1.STObject.from(json.metaData));
},
};
return [index, item, undefined];
}
/**
* Convert an entry to a pair Hash256 and ShaMapNode
*
* @param json JSON describing a ledger entry item
* @returns a tuple of index and item to be added to SHAMap
*/
function entryItemizer(json) {
const index = hash_256_1.Hash256.from(json.index);
const bytes = (0, binary_1.serializeObject)(json);
const item = {
hashPrefix() {
return hash_prefixes_1.HashPrefix.accountStateEntry;
},
toBytesSink(sink) {
sink.put(bytes);
},
};
return [index, item, undefined];
}
/**
* Function computing the hash of a transaction tree
*
* @param param An array of transaction objects to hash
* @returns A Hash256 object
*/
function transactionTreeHash(param) {
const itemizer = transactionItemizer;
return computeHash(itemizer, param);
}
exports.transactionTreeHash = transactionTreeHash;
/**
* Function computing the hash of accountState
*
* @param param A list of accountStates hash
* @returns A Hash256 object
*/
function accountStateHash(param) {
const itemizer = entryItemizer;
return computeHash(itemizer, param);
}
exports.accountStateHash = accountStateHash;
/**
* Serialize and hash a ledger header
*
* @param header a ledger header
* @returns the hash of header
*/
function ledgerHash(header) {
const hash = new hashes_1.Sha512Half();
hash.put(hash_prefixes_1.HashPrefix.ledgerHeader);
assert.ok(header.parent_close_time !== undefined);
assert.ok(header.close_flags !== undefined);
uint_32_1.UInt32.from(header.ledger_index).toBytesSink(hash);
uint_64_1.UInt64.from(bigInt(String(header.total_coins))).toBytesSink(hash);
hash_256_1.Hash256.from(header.parent_hash).toBytesSink(hash);
hash_256_1.Hash256.from(header.transaction_hash).toBytesSink(hash);
hash_256_1.Hash256.from(header.account_hash).toBytesSink(hash);
uint_32_1.UInt32.from(header.parent_close_time).toBytesSink(hash);
uint_32_1.UInt32.from(header.close_time).toBytesSink(hash);
uint_8_1.UInt8.from(header.close_time_resolution).toBytesSink(hash);
uint_8_1.UInt8.from(header.close_flags).toBytesSink(hash);
return hash.finish();
}
exports.ledgerHash = ledgerHash;
/**
* Decodes a serialized ledger header
*
* @param binary A serialized ledger header
* @returns A JSON object describing a ledger header
*/
function decodeLedgerData(binary) {
assert.ok(typeof binary === 'string', 'binary must be a hex string');
const parser = new binary_parser_1.BinaryParser(binary);
return {
ledger_index: parser.readUInt32(),
total_coins: parser.readType(uint_64_1.UInt64).valueOf().toString(),
parent_hash: parser.readType(hash_256_1.Hash256).toHex(),
transaction_hash: parser.readType(hash_256_1.Hash256).toHex(),
account_hash: parser.readType(hash_256_1.Hash256).toHex(),
parent_close_time: parser.readUInt32(),
close_time: parser.readUInt32(),
close_time_resolution: parser.readUInt8(),
close_flags: parser.readUInt8(),
};
}
exports.decodeLedgerData = decodeLedgerData;
//# sourceMappingURL=ledger-hashes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ledger-hashes.js","sourceRoot":"","sources":["../src/ledger-hashes.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAChC,qCAAyD;AACzD,mDAA4C;AAC5C,qCAAqC;AACrC,qCAA4D;AAC5D,+CAA0C;AAC1C,iDAA4C;AAC5C,6CAAwC;AACxC,6CAAwC;AACxC,2CAAsC;AACtC,0DAAqD;AAErD,sCAAsC;AAEtC;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,QAAoE,EACpE,SAA4B;IAE5B,MAAM,GAAG,GAAG,IAAI,eAAM,EAAE,CAAA;IACxB,SAAS,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAC3D,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AAUD;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,IAA2B;IAE3B,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,KAAK,GAAG,kBAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACrC,MAAM,IAAI,GAAG;QACX,UAAU;YACR,OAAO,0BAAU,CAAC,WAAW,CAAA;QAC/B,CAAC;QACD,WAAW,CAAC,IAAI;YACd,MAAM,UAAU,GAAG,IAAI,yBAAgB,CAAC,IAAI,C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M,GAAG,IAAI,4BAAY,CAAC,MAAM,CAAC,CAAA;IACvC,OAAO;QACL,YAAY,EAAE,MAAM,CAAC,UAAU,EAAE;QACjC,WAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,gBAAM,CAAC,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;QACzD,WAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,kBAAO,CAAC,CAAC,KAAK,EAAE;QAC7C,gBAAgB,EAAE,MAAM,CAAC,QAAQ,CAAC,kBAAO,CAAC,CAAC,KAAK,EAAE;QAClD,YAAY,EAAE,MAAM,CAAC,QAAQ,CAAC,kBAAO,CAAC,CAAC,KAAK,EAAE;QAC9C,iBAAiB,EAAE,MAAM,CAAC,UAAU,EAAE;QACtC,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE;QAC/B,qBAAqB,EAAE,MAAM,CAAC,SAAS,EAAE;QACzC,WAAW,EAAE,MAAM,CAAC,SAAS,EAAE;KAChC,CAAA;AACH,CAAC;AAE2D,4CAAgB"}
+22
View File
@@ -0,0 +1,22 @@
import { Decimal } from 'decimal.js';
import { Buffer } from 'buffer/';
/**
* class for encoding and decoding quality
*/
declare class quality {
/**
* Encode quality amount
*
* @param arg string representation of an amount
* @returns Serialized quality
*/
static encode(quality: string): Buffer;
/**
* Decode quality amount
*
* @param arg hex-string denoting serialized quality
* @returns deserialized quality
*/
static decode(quality: string): Decimal;
}
export { quality };
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.quality = void 0;
const types_1 = require("./types");
const decimal_js_1 = require("decimal.js");
const bigInt = require("big-integer");
const buffer_1 = require("buffer/");
/**
* class for encoding and decoding quality
*/
class quality {
/**
* Encode quality amount
*
* @param arg string representation of an amount
* @returns Serialized quality
*/
static encode(quality) {
const decimal = new decimal_js_1.Decimal(quality);
const exponent = decimal.e - 15;
const qualityString = decimal.times(`1e${-exponent}`).abs().toString();
const bytes = types_1.coreTypes.UInt64.from(bigInt(qualityString)).toBytes();
bytes[0] = exponent + 100;
return bytes;
}
/**
* Decode quality amount
*
* @param arg hex-string denoting serialized quality
* @returns deserialized quality
*/
static decode(quality) {
const bytes = buffer_1.Buffer.from(quality, 'hex').slice(-8);
const exponent = bytes[0] - 100;
const mantissa = new decimal_js_1.Decimal(`0x${bytes.slice(1).toString('hex')}`);
return mantissa.times(`1e${exponent}`);
}
}
exports.quality = quality;
//# sourceMappingURL=quality.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"quality.js","sourceRoot":"","sources":["../src/quality.ts"],"names":[],"mappings":";;;AAAA,mCAAmC;AACnC,2CAAoC;AACpC,sCAAsC;AACtC,oCAAgC;AAEhC;;GAEG;AACH,MAAM,OAAO;IACX;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,OAAe;QAC3B,MAAM,OAAO,GAAG,IAAI,oBAAO,CAAC,OAAO,CAAC,CAAA;QACpC,MAAM,QAAQ,GAAG,OAAO,CAAC,CAAC,GAAG,EAAE,CAAA;QAC/B,MAAM,aAAa,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAA;QACtE,MAAM,KAAK,GAAG,iBAAS,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,EAAE,CAAA;QACpE,KAAK,CAAC,CAAC,CAAC,GAAG,QAAQ,GAAG,GAAG,CAAA;QACzB,OAAO,KAAK,CAAA;IACd,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,OAAe;QAC3B,MAAM,KAAK,GAAG,eAAM,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QACnD,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAA;QAC/B,MAAM,QAAQ,GAAG,IAAI,oBAAO,CAAC,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QACnE,OAAO,QAAQ,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE,CAAC,CAAA;IACxC,CAAC;CACF;AAEQ,0BAAO"}
+98
View File
@@ -0,0 +1,98 @@
import { FieldInstance } from '../enums';
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
/**
* BinaryParser is used to compute fields and values from a HexString
*/
declare class BinaryParser {
private bytes;
/**
* Initialize bytes to a hex string
*
* @param hexBytes a hex string
*/
constructor(hexBytes: string);
/**
* Peek the first byte of the BinaryParser
*
* @returns The first byte of the BinaryParser
*/
peek(): number;
/**
* Consume the first n bytes of the BinaryParser
*
* @param n the number of bytes to skip
*/
skip(n: number): void;
/**
* read the first n bytes from the BinaryParser
*
* @param n The number of bytes to read
* @return The bytes
*/
read(n: number): Buffer;
/**
* Read an integer of given size
*
* @param n The number of bytes to read
* @return The number represented by those bytes
*/
readUIntN(n: number): number;
readUInt8(): number;
readUInt16(): number;
readUInt32(): number;
size(): number;
end(customEnd?: number): boolean;
/**
* Reads variable length encoded bytes
*
* @return The variable length bytes
*/
readVariableLength(): Buffer;
/**
* Reads the length of the variable length encoded bytes
*
* @return The length of the variable length encoded bytes
*/
readVariableLengthLength(): number;
/**
* Reads the field ordinal from the BinaryParser
*
* @return Field ordinal
*/
readFieldOrdinal(): number;
/**
* Read the field from the BinaryParser
*
* @return The field represented by the bytes at the head of the BinaryParser
*/
readField(): FieldInstance;
/**
* Read a given type from the BinaryParser
*
* @param type The type that you want to read from the BinaryParser
* @return The instance of that type read from the BinaryParser
*/
readType(type: typeof SerializedType): SerializedType;
/**
* Get the type associated with a given field
*
* @param field The field that you wan to get the type of
* @return The type associated with the given field
*/
typeForField(field: FieldInstance): typeof SerializedType;
/**
* Read value of the type specified by field from the BinaryParser
*
* @param field The field that you want to get the associated value for
* @return The value associated with the given field
*/
readFieldValue(field: FieldInstance): SerializedType;
/**
* Get the next field and value from the BinaryParser
*
* @return The field and value
*/
readFieldAndValue(): [FieldInstance, SerializedType];
}
export { BinaryParser };
+207
View File
@@ -0,0 +1,207 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryParser = void 0;
const assert = __importStar(require("assert"));
const enums_1 = require("../enums");
const buffer_1 = require("buffer/");
/**
* BinaryParser is used to compute fields and values from a HexString
*/
class BinaryParser {
/**
* Initialize bytes to a hex string
*
* @param hexBytes a hex string
*/
constructor(hexBytes) {
this.bytes = buffer_1.Buffer.from(hexBytes, 'hex');
}
/**
* Peek the first byte of the BinaryParser
*
* @returns The first byte of the BinaryParser
*/
peek() {
assert.ok(this.bytes.byteLength !== 0);
return this.bytes[0];
}
/**
* Consume the first n bytes of the BinaryParser
*
* @param n the number of bytes to skip
*/
skip(n) {
assert.ok(n <= this.bytes.byteLength);
this.bytes = this.bytes.slice(n);
}
/**
* read the first n bytes from the BinaryParser
*
* @param n The number of bytes to read
* @return The bytes
*/
read(n) {
assert.ok(n <= this.bytes.byteLength);
const slice = this.bytes.slice(0, n);
this.skip(n);
return slice;
}
/**
* Read an integer of given size
*
* @param n The number of bytes to read
* @return The number represented by those bytes
*/
readUIntN(n) {
assert.ok(0 < n && n <= 4, 'invalid n');
return this.read(n).reduce((a, b) => (a << 8) | b) >>> 0;
}
readUInt8() {
return this.readUIntN(1);
}
readUInt16() {
return this.readUIntN(2);
}
readUInt32() {
return this.readUIntN(4);
}
size() {
return this.bytes.byteLength;
}
end(customEnd) {
const length = this.bytes.byteLength;
return length === 0 || (customEnd !== undefined && length <= customEnd);
}
/**
* Reads variable length encoded bytes
*
* @return The variable length bytes
*/
readVariableLength() {
return this.read(this.readVariableLengthLength());
}
/**
* Reads the length of the variable length encoded bytes
*
* @return The length of the variable length encoded bytes
*/
readVariableLengthLength() {
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 variable length indicator');
}
/**
* Reads the field ordinal from the BinaryParser
*
* @return Field ordinal
*/
readFieldOrdinal() {
let type = this.readUInt8();
let nth = type & 15;
type >>= 4;
if (type === 0) {
type = this.readUInt8();
if (type === 0 || type < 16) {
throw new Error('Cannot read FieldOrdinal, type_code out of range');
}
}
if (nth === 0) {
nth = this.readUInt8();
if (nth === 0 || nth < 16) {
throw new Error('Cannot read FieldOrdinal, field_code out of range');
}
}
return (type << 16) | nth;
}
/**
* Read the field from the BinaryParser
*
* @return The field represented by the bytes at the head of the BinaryParser
*/
readField() {
return enums_1.Field.fromString(this.readFieldOrdinal().toString());
}
/**
* Read a given type from the BinaryParser
*
* @param type The type that you want to read from the BinaryParser
* @return The instance of that type read from the BinaryParser
*/
readType(type) {
return type.fromParser(this);
}
/**
* Get the type associated with a given field
*
* @param field The field that you wan to get the type of
* @return The type associated with the given field
*/
typeForField(field) {
return field.associatedType;
}
/**
* Read value of the type specified by field from the BinaryParser
*
* @param field The field that you want to get the associated value for
* @return The value associated with the given field
*/
readFieldValue(field) {
const type = this.typeForField(field);
if (!type) {
throw new Error(`unsupported: (${field.name}, ${field.type.name})`);
}
const sizeHint = field.isVariableLengthEncoded
? this.readVariableLengthLength()
: undefined;
const value = type.fromParser(this, sizeHint);
if (value === undefined) {
throw new Error(`fromParser for (${field.name}, ${field.type.name}) -> undefined `);
}
return value;
}
/**
* Get the next field and value from the BinaryParser
*
* @return The field and value
*/
readFieldAndValue() {
const field = this.readField();
return [field, this.readFieldValue(field)];
}
}
exports.BinaryParser = BinaryParser;
//# sourceMappingURL=binary-parser.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"binary-parser.js","sourceRoot":"","sources":["../../src/serdes/binary-parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAChC,oCAA+C;AAE/C,oCAAgC;AAEhC;;GAEG;AACH,MAAM,YAAY;IAGhB;;;;OAIG;IACH,YAAY,QAAgB;QAC1B,IAAI,CAAC,KAAK,GAAG,eAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAC3C,CAAC;IAED;;;;OAIG;IACH,IAAI;QACF,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,CAAC,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,CAAS;QACZ,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACrC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAClC,CAAC;IAED;;;;;OAKG;IACH,IAAI,CAAC,CAAS;QACZ,MAAM,CAAC,EAAE,CAAC,CAAC,IAA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AAS;QACP,OAAO,aAAK,CAAC,UAAU,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;IAC7D,CAAC;IAED;;;;;OAKG;IACH,QAAQ,CAAC,IAA2B;QAClC,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;IAC9B,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,KAAoB;QAC/B,OAAO,KAAK,CAAC,cAAc,CAAA;IAC7B,CAAC;IAED;;;;;OAKG;IACH,cAAc,CAAC,KAAoB;QACjC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAA;QACrC,IAAI,CAAC,IAAI,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,iBAAiB,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAA;SACpE;QACD,MAAM,QAAQ,GAAG,KAAK,CAAC,uBAAuB;YAC5C,CAAC,CAAC,IAAI,CAAC,wBAAwB,EAAE;YACjC,CAAC,CAAC,SAAS,CAAA;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;QAC7C,IAAI,KAAK,KAAK,SAAS,EAAE;YACvB,MAAM,IAAI,KAAK,CACb,mBAAmB,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,iBAAiB,CACnE,CAAA;SACF;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED;;;;OAIG;IACH,iBAAiB;QACf,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,CAAA;QAC9B,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAA;IAC5C,CAAC;CACF;AAEQ,oCAAY"}
+82
View File
@@ -0,0 +1,82 @@
import { FieldInstance } from '../enums';
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
/**
* Bytes list is a collection of buffer objects
*/
declare class BytesList {
private bytesArray;
/**
* Get the total number of bytes in the BytesList
*
* @return the number of bytes
*/
getLength(): number;
/**
* Put bytes in the BytesList
*
* @param bytesArg A Buffer
* @return this BytesList
*/
put(bytesArg: Buffer): BytesList;
/**
* Write this BytesList to the back of another bytes list
*
* @param list The BytesList to write to
*/
toBytesSink(list: BytesList): void;
toBytes(): Buffer;
toHex(): string;
}
/**
* BinarySerializer is used to write fields and values to buffers
*/
declare class BinarySerializer {
private sink;
constructor(sink: BytesList);
/**
* Write a value to this BinarySerializer
*
* @param value a SerializedType value
*/
write(value: SerializedType): void;
/**
* Write bytes to this BinarySerializer
*
* @param bytes the bytes to write
*/
put(bytes: Buffer): void;
/**
* Write a value of a given type to this BinarySerializer
*
* @param type the type to write
* @param value a value of that type
*/
writeType(type: typeof SerializedType, value: SerializedType): void;
/**
* Write BytesList to this BinarySerializer
*
* @param bl BytesList to write to BinarySerializer
*/
writeBytesList(bl: BytesList): void;
/**
* Calculate the header of Variable Length encoded bytes
*
* @param length the length of the bytes
*/
private encodeVariableLength;
/**
* Write field and value to BinarySerializer
*
* @param field field to write to BinarySerializer
* @param value value to write to BinarySerializer
*/
writeFieldAndValue(field: FieldInstance, value: SerializedType, isUnlModifyWorkaround?: boolean): void;
/**
* Write a variable length encoded value to the BinarySerializer
*
* @param value length encoded value to write to BytesList
*/
writeLengthEncoded(value: SerializedType, isUnlModifyWorkaround?: boolean): void;
}
export { BytesList, BinarySerializer };
+172
View File
@@ -0,0 +1,172 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinarySerializer = exports.BytesList = void 0;
const assert = __importStar(require("assert"));
const buffer_1 = require("buffer/");
/**
* Bytes list is a collection of buffer objects
*/
class BytesList {
constructor() {
this.bytesArray = [];
}
/**
* Get the total number of bytes in the BytesList
*
* @return the number of bytes
*/
getLength() {
return buffer_1.Buffer.concat(this.bytesArray).byteLength;
}
/**
* Put bytes in the BytesList
*
* @param bytesArg A Buffer
* @return this BytesList
*/
put(bytesArg) {
const bytes = buffer_1.Buffer.from(bytesArg); // Temporary, to catch instances of Uint8Array being passed in
this.bytesArray.push(bytes);
return this;
}
/**
* Write this BytesList to the back of another bytes list
*
* @param list The BytesList to write to
*/
toBytesSink(list) {
list.put(this.toBytes());
}
toBytes() {
return buffer_1.Buffer.concat(this.bytesArray);
}
toHex() {
return this.toBytes().toString('hex').toUpperCase();
}
}
exports.BytesList = BytesList;
/**
* BinarySerializer is used to write fields and values to buffers
*/
class BinarySerializer {
constructor(sink) {
this.sink = new BytesList();
this.sink = sink;
}
/**
* Write a value to this BinarySerializer
*
* @param value a SerializedType value
*/
write(value) {
value.toBytesSink(this.sink);
}
/**
* Write bytes to this BinarySerializer
*
* @param bytes the bytes to write
*/
put(bytes) {
this.sink.put(bytes);
}
/**
* Write a value of a given type to this BinarySerializer
*
* @param type the type to write
* @param value a value of that type
*/
writeType(type, value) {
this.write(type.from(value));
}
/**
* Write BytesList to this BinarySerializer
*
* @param bl BytesList to write to BinarySerializer
*/
writeBytesList(bl) {
bl.toBytesSink(this.sink);
}
/**
* Calculate the header of Variable Length encoded bytes
*
* @param length the length of the bytes
*/
encodeVariableLength(length) {
const lenBytes = buffer_1.Buffer.alloc(3);
if (length <= 192) {
lenBytes[0] = length;
return lenBytes.slice(0, 1);
}
else if (length <= 12480) {
length -= 193;
lenBytes[0] = 193 + (length >>> 8);
lenBytes[1] = length & 0xff;
return lenBytes.slice(0, 2);
}
else if (length <= 918744) {
length -= 12481;
lenBytes[0] = 241 + (length >>> 16);
lenBytes[1] = (length >> 8) & 0xff;
lenBytes[2] = length & 0xff;
return lenBytes.slice(0, 3);
}
throw new Error('Overflow error');
}
/**
* Write field and value to BinarySerializer
*
* @param field field to write to BinarySerializer
* @param value value to write to BinarySerializer
*/
writeFieldAndValue(field, value, isUnlModifyWorkaround = false) {
const associatedValue = field.associatedType.from(value);
assert.ok(associatedValue.toBytesSink !== undefined);
assert.ok(field.name !== undefined);
this.sink.put(field.header);
if (field.isVariableLengthEncoded) {
this.writeLengthEncoded(associatedValue, isUnlModifyWorkaround);
}
else {
associatedValue.toBytesSink(this.sink);
}
}
/**
* Write a variable length encoded value to the BinarySerializer
*
* @param value length encoded value to write to BytesList
*/
writeLengthEncoded(value, isUnlModifyWorkaround = false) {
const bytes = new BytesList();
if (!isUnlModifyWorkaround) {
// this part doesn't happen for the Account field in a UNLModify transaction
value.toBytesSink(bytes);
}
this.put(this.encodeVariableLength(bytes.getLength()));
this.writeBytesList(bytes);
}
}
exports.BinarySerializer = BinarySerializer;
//# sourceMappingURL=binary-serializer.js.map
@@ -0,0 +1 @@
{"version":3,"file":"binary-serializer.js","sourceRoot":"","sources":["../../src/serdes/binary-serializer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAGhC,oCAAgC;AAEhC;;GAEG;AACH,MAAM,SAAS;IAAf;QACU,eAAU,GAAkB,EAAE,CAAA;IAuCxC,CAAC;IArCC;;;;OAIG;IACI,SAAS;QACd,OAAO,eAAM,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,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AE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAA;QAEnC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;QAE3B,IAAI,KAAK,CAAC,uBAAuB,EAAE;YACjC,IAAI,CAAC,kBAAkB,CAAC,eAAe,EAAE,qBAAqB,CAAC,CAAA;SAChE;aAAM;YACL,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;SACvC;IACH,CAAC;IAED;;;;OAIG;IACI,kBAAkB,CACvB,KAAqB,EACrB,qBAAqB,GAAG,KAAK;QAE7B,MAAM,KAAK,GAAG,IAAI,SAAS,EAAE,CAAA;QAC7B,IAAI,CAAC,qBAAqB,EAAE;YAC1B,4EAA4E;YAC5E,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;SACzB;QACD,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAA;QACtD,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAA;IAC5B,CAAC;CACF;AAEmB,4CAAgB"}
+103
View File
@@ -0,0 +1,103 @@
import { Hash256 } from './types/hash-256';
import { BytesList } from './serdes/binary-serializer';
import { Buffer } from 'buffer/';
/**
* Abstract class describing a SHAMapNode
*/
declare abstract class ShaMapNode {
abstract hashPrefix(): Buffer;
abstract isLeaf(): boolean;
abstract isInner(): boolean;
abstract toBytesSink(list: BytesList): void;
abstract hash(): Hash256;
}
/**
* Class describing a Leaf of SHAMap
*/
declare class ShaMapLeaf extends ShaMapNode {
index: Hash256;
item?: ShaMapNode | undefined;
constructor(index: Hash256, item?: ShaMapNode | undefined);
/**
* @returns true as ShaMapLeaf is a leaf node
*/
isLeaf(): boolean;
/**
* @returns false as ShaMapLeaf is not an inner node
*/
isInner(): boolean;
/**
* Get the prefix of the this.item
*
* @returns The hash prefix, unless this.item is undefined, then it returns an empty Buffer
*/
hashPrefix(): Buffer;
/**
* Hash the bytes representation of this
*
* @returns hash of this.item concatenated with this.index
*/
hash(): Hash256;
/**
* Write the bytes representation of this to a BytesList
* @param list BytesList to write bytes to
*/
toBytesSink(list: BytesList): void;
}
/**
* Class defining an Inner Node of a SHAMap
*/
declare class ShaMapInner extends ShaMapNode {
private depth;
private slotBits;
private branches;
constructor(depth?: number);
/**
* @returns true as ShaMapInner is an inner node
*/
isInner(): boolean;
/**
* @returns false as ShaMapInner is not a leaf node
*/
isLeaf(): boolean;
/**
* Get the hash prefix for this node
*
* @returns hash prefix describing an inner node
*/
hashPrefix(): Buffer;
/**
* Set a branch of this node to be another node
*
* @param slot Slot to add branch to this.branches
* @param branch Branch to add
*/
setBranch(slot: number, branch: ShaMapNode): void;
/**
* @returns true if node is empty
*/
empty(): boolean;
/**
* Compute the hash of this node
*
* @returns The hash of this node
*/
hash(): Hash256;
/**
* Writes the bytes representation of this node to a BytesList
*
* @param list BytesList to write bytes to
*/
toBytesSink(list: BytesList): void;
/**
* Add item to the SHAMap
*
* @param index Hash of the index of the item being inserted
* @param item Item to insert in the map
* @param leaf Leaf node to insert when branch doesn't exist
*/
addItem(index?: Hash256, item?: ShaMapNode, leaf?: ShaMapLeaf): void;
}
declare class ShaMap extends ShaMapInner {
}
export { ShaMap, ShaMapNode, ShaMapLeaf };
+170
View File
@@ -0,0 +1,170 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShaMapLeaf = exports.ShaMapNode = exports.ShaMap = void 0;
const assert_1 = require("assert");
const types_1 = require("./types");
const hash_prefixes_1 = require("./hash-prefixes");
const hashes_1 = require("./hashes");
const buffer_1 = require("buffer/");
/**
* Abstract class describing a SHAMapNode
*/
class ShaMapNode {
}
exports.ShaMapNode = ShaMapNode;
/**
* Class describing a Leaf of SHAMap
*/
class ShaMapLeaf extends ShaMapNode {
constructor(index, item) {
super();
this.index = index;
this.item = item;
}
/**
* @returns true as ShaMapLeaf is a leaf node
*/
isLeaf() {
return true;
}
/**
* @returns false as ShaMapLeaf is not an inner node
*/
isInner() {
return false;
}
/**
* Get the prefix of the this.item
*
* @returns The hash prefix, unless this.item is undefined, then it returns an empty Buffer
*/
hashPrefix() {
return this.item === undefined ? buffer_1.Buffer.alloc(0) : this.item.hashPrefix();
}
/**
* Hash the bytes representation of this
*
* @returns hash of this.item concatenated with this.index
*/
hash() {
const hash = hashes_1.Sha512Half.put(this.hashPrefix());
this.toBytesSink(hash);
return hash.finish();
}
/**
* Write the bytes representation of this to a BytesList
* @param list BytesList to write bytes to
*/
toBytesSink(list) {
if (this.item !== undefined) {
this.item.toBytesSink(list);
}
this.index.toBytesSink(list);
}
}
exports.ShaMapLeaf = ShaMapLeaf;
/**
* Class defining an Inner Node of a SHAMap
*/
class ShaMapInner extends ShaMapNode {
constructor(depth = 0) {
super();
this.depth = depth;
this.slotBits = 0;
this.branches = Array(16);
}
/**
* @returns true as ShaMapInner is an inner node
*/
isInner() {
return true;
}
/**
* @returns false as ShaMapInner is not a leaf node
*/
isLeaf() {
return false;
}
/**
* Get the hash prefix for this node
*
* @returns hash prefix describing an inner node
*/
hashPrefix() {
return hash_prefixes_1.HashPrefix.innerNode;
}
/**
* Set a branch of this node to be another node
*
* @param slot Slot to add branch to this.branches
* @param branch Branch to add
*/
setBranch(slot, branch) {
this.slotBits = this.slotBits | (1 << slot);
this.branches[slot] = branch;
}
/**
* @returns true if node is empty
*/
empty() {
return this.slotBits === 0;
}
/**
* Compute the hash of this node
*
* @returns The hash of this node
*/
hash() {
if (this.empty()) {
return types_1.coreTypes.Hash256.ZERO_256;
}
const hash = hashes_1.Sha512Half.put(this.hashPrefix());
this.toBytesSink(hash);
return hash.finish();
}
/**
* Writes the bytes representation of this node to a BytesList
*
* @param list BytesList to write bytes to
*/
toBytesSink(list) {
for (let i = 0; i < this.branches.length; i++) {
const branch = this.branches[i];
const hash = branch ? branch.hash() : types_1.coreTypes.Hash256.ZERO_256;
hash.toBytesSink(list);
}
}
/**
* Add item to the SHAMap
*
* @param index Hash of the index of the item being inserted
* @param item Item to insert in the map
* @param leaf Leaf node to insert when branch doesn't exist
*/
addItem(index, item, leaf) {
assert_1.strict.ok(index !== undefined);
if (index !== undefined) {
const nibble = index.nibblet(this.depth);
const existing = this.branches[nibble];
if (existing === undefined) {
this.setBranch(nibble, leaf || new ShaMapLeaf(index, item));
}
else if (existing instanceof ShaMapLeaf) {
const newInner = new ShaMapInner(this.depth + 1);
newInner.addItem(existing.index, undefined, existing);
newInner.addItem(index, item, leaf);
this.setBranch(nibble, newInner);
}
else if (existing instanceof ShaMapInner) {
existing.addItem(index, item, leaf);
}
else {
throw new Error('invalid ShaMap.addItem call');
}
}
}
}
class ShaMap extends ShaMapInner {
}
exports.ShaMap = ShaMap;
//# sourceMappingURL=shamap.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"shamap.js","sourceRoot":"","sources":["../src/shamap.ts"],"names":[],"mappings":";;;AAAA,mCAAyC;AACzC,mCAAmC;AACnC,mDAA4C;AAC5C,qCAAqC;AAGrC,oCAAgC;AAEhC;;GAEG;AACH,MAAe,UAAU;CAMxB;AAsKgB,gCAAU;AApK3B;;GAEG;AACH,MAAM,UAAW,SAAQ,UAAU;IACjC,YAAmB,KAAc,EAAS,IAAiB;QACzD,KAAK,EAAE,CAAA;QADU,UAAK,GAAL,KAAK,CAAS;QAAS,SAAI,GAAJ,IAAI,CAAa;IAE3D,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,KAAK,CAAA;IACd,CAAC;IAED;;;;OAIG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,eAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAA;IAC3E,CAAC;IAED;;;;OAIG;IACH,IAAI;QACF,MAAM,IAAI,GA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OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;gBACrD,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;gBACnC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;aACjC;iBAAM,IAAI,QAAQ,YAAY,WAAW,EAAE;gBAC1C,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;aACpC;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;aAC/C;SACF;IACH,CAAC;CACF;AAED,MAAM,MAAO,SAAQ,WAAW;CAAG;AAE1B,wBAAM"}
+36
View File
@@ -0,0 +1,36 @@
import { Hash160 } from './hash-160';
import { Buffer } from 'buffer/';
/**
* Class defining how to encode and decode an AccountID
*/
declare class AccountID extends Hash160 {
static readonly defaultAccountID: AccountID;
constructor(bytes?: Buffer);
/**
* Defines how to construct an AccountID
*
* @param value either an existing AccountID, a hex-string, or a base58 r-Address
* @returns an AccountID object
*/
static from<T extends Hash160 | string>(value: T): AccountID;
/**
* Defines how to build an AccountID from a base58 r-Address
*
* @param value a base58 r-Address
* @returns an AccountID object
*/
static fromBase58(value: string): AccountID;
/**
* Overload of toJSON
*
* @returns the base58 string for this AccountID
*/
toJSON(): string;
/**
* Defines how to encode AccountID into a base58 address
*
* @returns the base58 string defined by this.bytes
*/
toBase58(): string;
}
export { AccountID };
+71
View File
@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountID = void 0;
const ripple_address_codec_1 = require("ripple-address-codec");
const hash_160_1 = require("./hash-160");
const buffer_1 = require("buffer/");
const HEX_REGEX = /^[A-F0-9]{40}$/;
/**
* Class defining how to encode and decode an AccountID
*/
class AccountID extends hash_160_1.Hash160 {
constructor(bytes) {
super(bytes !== null && bytes !== void 0 ? bytes : AccountID.defaultAccountID.bytes);
}
/**
* Defines how to construct an AccountID
*
* @param value either an existing AccountID, a hex-string, or a base58 r-Address
* @returns an AccountID object
*/
static from(value) {
if (value instanceof AccountID) {
return value;
}
if (typeof value === 'string') {
if (value === '') {
return new AccountID();
}
return HEX_REGEX.test(value)
? new AccountID(buffer_1.Buffer.from(value, 'hex'))
: this.fromBase58(value);
}
throw new Error('Cannot construct AccountID from value given');
}
/**
* Defines how to build an AccountID from a base58 r-Address
*
* @param value a base58 r-Address
* @returns an AccountID object
*/
static fromBase58(value) {
if ((0, ripple_address_codec_1.isValidXAddress)(value)) {
const classic = (0, ripple_address_codec_1.xAddressToClassicAddress)(value);
if (classic.tag !== false)
throw new Error('Only allowed to have tag on Account or Destination');
value = classic.classicAddress;
}
return new AccountID(buffer_1.Buffer.from((0, ripple_address_codec_1.decodeAccountID)(value)));
}
/**
* Overload of toJSON
*
* @returns the base58 string for this AccountID
*/
toJSON() {
return this.toBase58();
}
/**
* Defines how to encode AccountID into a base58 address
*
* @returns the base58 string defined by this.bytes
*/
toBase58() {
/* eslint-disable @typescript-eslint/no-explicit-any */
return (0, ripple_address_codec_1.encodeAccountID)(this.bytes);
/* eslint-enable @typescript-eslint/no-explicit-any */
}
}
exports.AccountID = AccountID;
AccountID.defaultAccountID = new AccountID(buffer_1.Buffer.alloc(20));
//# sourceMappingURL=account-id.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"account-id.js","sourceRoot":"","sources":["../../src/types/account-id.ts"],"names":[],"mappings":";;;AAAA,+DAK6B;AAC7B,yCAAoC;AACpC,oCAAgC;AAEhC,MAAM,SAAS,GAAG,gBAAgB,CAAA;AAElC;;GAEG;AACH,MAAM,SAAU,SAAQ,kBAAO;IAG7B,YAAY,KAAc;QACxB,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,SAAS,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;IAClD,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,IAAI,CAA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 @@
import { BinaryParser } from '../serdes/binary-parser';
import { JsonObject, SerializedType } from './serialized-type';
import { Buffer } from 'buffer/';
/**
* Interface for JSON objects that represent amounts
*/
interface AmountObject extends JsonObject {
value: string;
currency: string;
issuer: string;
}
/**
* Class for serializing/Deserializing Amounts
*/
declare class Amount extends SerializedType {
static defaultAmount: Amount;
constructor(bytes: Buffer);
/**
* Construct an amount from an IOU or string amount
*
* @param value An Amount, object representing an IOU, or a string
* representing an integer amount
* @returns An Amount object
*/
static from<T extends Amount | AmountObject | string>(value: T): Amount;
/**
* Read an amount from a BinaryParser
*
* @param parser BinaryParser to read the Amount from
* @returns An Amount object
*/
static fromParser(parser: BinaryParser): Amount;
/**
* Get the JSON representation of this Amount
*
* @returns the JSON interpretation of this.bytes
*/
toJSON(): AmountObject | string;
/**
* Validate XRP amount
*
* @param amount String representing XRP amount
* @returns void, but will throw if invalid amount
*/
private static assertXrpIsValid;
/**
* Validate IOU.value amount
*
* @param decimal Decimal.js object representing IOU.value
* @returns void, but will throw if invalid amount
*/
private static assertIouIsValid;
/**
* Ensure that the value after being multiplied by the exponent does not
* contain a decimal.
*
* @param decimal a Decimal object
* @returns a string of the object without a decimal
*/
private static verifyNoDecimal;
/**
* Test if this amount is in units of Native Currency(XRP)
*
* @returns true if Native (XRP)
*/
private isNative;
}
export { Amount, AmountObject };
+207
View File
@@ -0,0 +1,207 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Amount = void 0;
const decimal_js_1 = require("decimal.js");
const binary_parser_1 = require("../serdes/binary-parser");
const account_id_1 = require("./account-id");
const currency_1 = require("./currency");
const serialized_type_1 = require("./serialized-type");
const bigInt = require("big-integer");
const buffer_1 = require("buffer/");
/**
* Constants for validating amounts
*/
const MIN_IOU_EXPONENT = -96;
const MAX_IOU_EXPONENT = 80;
const MAX_IOU_PRECISION = 16;
const MAX_DROPS = new decimal_js_1.Decimal('1e17');
const MIN_XRP = new decimal_js_1.Decimal('1e-6');
const mask = bigInt(0x00000000ffffffff);
/**
* decimal.js configuration for Amount IOUs
*/
decimal_js_1.Decimal.config({
toExpPos: MAX_IOU_EXPONENT + MAX_IOU_PRECISION,
toExpNeg: MIN_IOU_EXPONENT - MAX_IOU_PRECISION,
});
/**
* Type guard for AmountObject
*/
function isAmountObject(arg) {
const keys = Object.keys(arg).sort();
return (keys.length === 3 &&
keys[0] === 'currency' &&
keys[1] === 'issuer' &&
keys[2] === 'value');
}
/**
* Class for serializing/Deserializing Amounts
*/
class Amount extends serialized_type_1.SerializedType {
constructor(bytes) {
super(bytes !== null && bytes !== void 0 ? bytes : Amount.defaultAmount.bytes);
}
/**
* Construct an amount from an IOU or string amount
*
* @param value An Amount, object representing an IOU, or a string
* representing an integer amount
* @returns An Amount object
*/
static from(value) {
if (value instanceof Amount) {
return value;
}
let amount = buffer_1.Buffer.alloc(8);
if (typeof value === 'string') {
Amount.assertXrpIsValid(value);
const number = bigInt(value);
const intBuf = [buffer_1.Buffer.alloc(4), buffer_1.Buffer.alloc(4)];
intBuf[0].writeUInt32BE(Number(number.shiftRight(32)), 0);
intBuf[1].writeUInt32BE(Number(number.and(mask)), 0);
amount = buffer_1.Buffer.concat(intBuf);
amount[0] |= 0x40;
return new Amount(amount);
}
if (isAmountObject(value)) {
const number = new decimal_js_1.Decimal(value.value);
Amount.assertIouIsValid(number);
if (number.isZero()) {
amount[0] |= 0x80;
}
else {
const integerNumberString = number
.times(`1e${-(number.e - 15)}`)
.abs()
.toString();
const num = bigInt(integerNumberString);
const intBuf = [buffer_1.Buffer.alloc(4), buffer_1.Buffer.alloc(4)];
intBuf[0].writeUInt32BE(Number(num.shiftRight(32)), 0);
intBuf[1].writeUInt32BE(Number(num.and(mask)), 0);
amount = buffer_1.Buffer.concat(intBuf);
amount[0] |= 0x80;
if (number.gt(new decimal_js_1.Decimal(0))) {
amount[0] |= 0x40;
}
const exponent = number.e - 15;
const exponentByte = 97 + exponent;
amount[0] |= exponentByte >>> 2;
amount[1] |= (exponentByte & 0x03) << 6;
}
const currency = currency_1.Currency.from(value.currency).toBytes();
const issuer = account_id_1.AccountID.from(value.issuer).toBytes();
return new Amount(buffer_1.Buffer.concat([amount, currency, issuer]));
}
throw new Error('Invalid type to construct an Amount');
}
/**
* Read an amount from a BinaryParser
*
* @param parser BinaryParser to read the Amount from
* @returns An Amount object
*/
static fromParser(parser) {
const isXRP = parser.peek() & 0x80;
const numBytes = isXRP ? 48 : 8;
return new Amount(parser.read(numBytes));
}
/**
* Get the JSON representation of this Amount
*
* @returns the JSON interpretation of this.bytes
*/
toJSON() {
if (this.isNative()) {
const bytes = this.bytes;
const isPositive = bytes[0] & 0x40;
const sign = isPositive ? '' : '-';
bytes[0] &= 0x3f;
const msb = bigInt(bytes.slice(0, 4).readUInt32BE(0));
const lsb = bigInt(bytes.slice(4).readUInt32BE(0));
const num = msb.shiftLeft(32).or(lsb);
return `${sign}${num.toString()}`;
}
else {
const parser = new binary_parser_1.BinaryParser(this.toString());
const mantissa = parser.read(8);
const currency = currency_1.Currency.fromParser(parser);
const issuer = account_id_1.AccountID.fromParser(parser);
const b1 = mantissa[0];
const b2 = mantissa[1];
const isPositive = b1 & 0x40;
const sign = isPositive ? '' : '-';
const exponent = ((b1 & 0x3f) << 2) + ((b2 & 0xff) >> 6) - 97;
mantissa[0] = 0;
mantissa[1] &= 0x3f;
const value = new decimal_js_1.Decimal(`${sign}0x${mantissa.toString('hex')}`).times(`1e${exponent}`);
Amount.assertIouIsValid(value);
return {
value: value.toString(),
currency: currency.toJSON(),
issuer: issuer.toJSON(),
};
}
}
/**
* Validate XRP amount
*
* @param amount String representing XRP amount
* @returns void, but will throw if invalid amount
*/
static assertXrpIsValid(amount) {
if (amount.indexOf('.') !== -1) {
throw new Error(`${amount.toString()} is an illegal amount`);
}
const decimal = new decimal_js_1.Decimal(amount);
if (!decimal.isZero()) {
if (decimal.lt(MIN_XRP) || decimal.gt(MAX_DROPS)) {
throw new Error(`${amount.toString()} is an illegal amount`);
}
}
}
/**
* Validate IOU.value amount
*
* @param decimal Decimal.js object representing IOU.value
* @returns void, but will throw if invalid amount
*/
static assertIouIsValid(decimal) {
if (!decimal.isZero()) {
const p = decimal.precision();
const e = decimal.e - 15;
if (p > MAX_IOU_PRECISION ||
e > MAX_IOU_EXPONENT ||
e < MIN_IOU_EXPONENT) {
throw new Error('Decimal precision out of range');
}
this.verifyNoDecimal(decimal);
}
}
/**
* Ensure that the value after being multiplied by the exponent does not
* contain a decimal.
*
* @param decimal a Decimal object
* @returns a string of the object without a decimal
*/
static verifyNoDecimal(decimal) {
const integerNumberString = decimal
.times(`1e${-(decimal.e - 15)}`)
.abs()
.toString();
if (integerNumberString.indexOf('.') !== -1) {
throw new Error('Decimal place found in integerNumberString');
}
}
/**
* Test if this amount is in units of Native Currency(XRP)
*
* @returns true if Native (XRP)
*/
isNative() {
return (this.bytes[0] & 0x80) === 0;
}
}
exports.Amount = Amount;
Amount.defaultAmount = new Amount(buffer_1.Buffer.from('4000000000000000', 'hex'));
//# sourceMappingURL=amount.js.map
File diff suppressed because one or more lines are too long
+25
View File
@@ -0,0 +1,25 @@
import { SerializedType } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**
* Variable length encoded type
*/
declare class Blob extends SerializedType {
constructor(bytes: Buffer);
/**
* Defines how to read a Blob from a BinaryParser
*
* @param parser The binary parser to read the Blob from
* @param hint The length of the blob, computed by readVariableLengthLength() and passed in
* @returns A Blob object
*/
static fromParser(parser: BinaryParser, hint: number): Blob;
/**
* Create a Blob object from a hex-string
*
* @param value existing Blob object or a hex-string
* @returns A Blob object
*/
static from<T extends Blob | string>(value: T): Blob;
}
export { Blob };
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Blob = void 0;
const serialized_type_1 = require("./serialized-type");
const buffer_1 = require("buffer/");
/**
* Variable length encoded type
*/
class Blob extends serialized_type_1.SerializedType {
constructor(bytes) {
super(bytes);
}
/**
* Defines how to read a Blob from a BinaryParser
*
* @param parser The binary parser to read the Blob from
* @param hint The length of the blob, computed by readVariableLengthLength() and passed in
* @returns A Blob object
*/
static fromParser(parser, hint) {
return new Blob(parser.read(hint));
}
/**
* Create a Blob object from a hex-string
*
* @param value existing Blob object or a hex-string
* @returns A Blob object
*/
static from(value) {
if (value instanceof Blob) {
return value;
}
if (typeof value === 'string') {
return new Blob(buffer_1.Buffer.from(value, 'hex'));
}
throw new Error('Cannot construct Blob from value given');
}
}
exports.Blob = Blob;
//# sourceMappingURL=blob.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blob.js","sourceRoot":"","sources":["../../src/types/blob.ts"],"names":[],"mappings":";;;AAAA,uDAAkD;AAElD,oCAAgC;AAEhC;;GAEG;AACH,MAAM,IAAK,SAAQ,gCAAc;IAC/B,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,CAAC,CAAA;IACd,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,MAAoB,EAAE,IAAY;QAClD,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpC,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,IAAI,CAA0B,KAAQ;QAC3C,IAAI,KAAK,YAAY,IAAI,EAAE;YACzB,OAAO,KAAK,CAAA;SACb;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,OAAO,IAAI,IAAI,CAAC,eAAM,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;SAC3C;QAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IAC3D,CAAC;CACF;AAEQ,oBAAI"}
+29
View File
@@ -0,0 +1,29 @@
import { Hash160 } from './hash-160';
import { Buffer } from 'buffer/';
/**
* Class defining how to encode and decode Currencies
*/
declare class Currency extends Hash160 {
static readonly XRP: Currency;
private readonly _iso;
constructor(byteBuf: Buffer);
/**
* Return the ISO code of this currency
*
* @returns ISO code if it exists, else null
*/
iso(): string | null;
/**
* Constructs a Currency object
*
* @param val Currency object or a string representation of a currency
*/
static from<T extends Hash160 | string>(value: T): Currency;
/**
* Gets the JSON representation of a currency
*
* @returns JSON representation
*/
toJSON(): string;
}
export { Currency };
+127
View File
@@ -0,0 +1,127 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Currency = void 0;
const hash_160_1 = require("./hash-160");
const buffer_1 = require("buffer/");
const XRP_HEX_REGEX = /^0{40}$/;
const ISO_REGEX = /^[A-Z0-9a-z?!@#$%^&*(){}[\]|]{3}$/;
const HEX_REGEX = /^[A-F0-9]{40}$/;
// eslint-disable-next-line no-control-regex
const STANDARD_FORMAT_HEX_REGEX = /^0{24}[\x00-\x7F]{6}0{10}$/;
/**
* Convert an ISO code to a currency bytes representation
*/
function isoToBytes(iso) {
const bytes = buffer_1.Buffer.alloc(20);
if (iso !== 'XRP') {
const isoBytes = iso.split('').map((c) => c.charCodeAt(0));
bytes.set(isoBytes, 12);
}
return bytes;
}
/**
* Tests if ISO is a valid iso code
*/
function isIsoCode(iso) {
return ISO_REGEX.test(iso);
}
function isoCodeFromHex(code) {
const iso = code.toString();
if (iso === 'XRP') {
return null;
}
if (isIsoCode(iso)) {
return iso;
}
return null;
}
/**
* Tests if hex is a valid hex-string
*/
function isHex(hex) {
return HEX_REGEX.test(hex);
}
/**
* Tests if a string is a valid representation of a currency
*/
function isStringRepresentation(input) {
return input.length === 3 || isHex(input);
}
/**
* Tests if a Buffer is a valid representation of a currency
*/
function isBytesArray(bytes) {
return bytes.byteLength === 20;
}
/**
* Ensures that a value is a valid representation of a currency
*/
function isValidRepresentation(input) {
return input instanceof buffer_1.Buffer
? isBytesArray(input)
: isStringRepresentation(input);
}
/**
* Generate bytes from a string or buffer representation of a currency
*/
function bytesFromRepresentation(input) {
if (!isValidRepresentation(input)) {
throw new Error(`Unsupported Currency representation: ${input}`);
}
return input.length === 3 ? isoToBytes(input) : buffer_1.Buffer.from(input, 'hex');
}
/**
* Class defining how to encode and decode Currencies
*/
class Currency extends hash_160_1.Hash160 {
constructor(byteBuf) {
super(byteBuf !== null && byteBuf !== void 0 ? byteBuf : Currency.XRP.bytes);
const hex = this.bytes.toString('hex');
if (XRP_HEX_REGEX.test(hex)) {
this._iso = 'XRP';
}
else if (STANDARD_FORMAT_HEX_REGEX.test(hex)) {
this._iso = isoCodeFromHex(this.bytes.slice(12, 15));
}
else {
this._iso = null;
}
}
/**
* Return the ISO code of this currency
*
* @returns ISO code if it exists, else null
*/
iso() {
return this._iso;
}
/**
* Constructs a Currency object
*
* @param val Currency object or a string representation of a currency
*/
static from(value) {
if (value instanceof Currency) {
return value;
}
if (typeof value === 'string') {
return new Currency(bytesFromRepresentation(value));
}
throw new Error('Cannot construct Currency from value given');
}
/**
* Gets the JSON representation of a currency
*
* @returns JSON representation
*/
toJSON() {
const iso = this.iso();
if (iso !== null) {
return iso;
}
return this.bytes.toString('hex').toUpperCase();
}
}
exports.Currency = Currency;
Currency.XRP = new Currency(buffer_1.Buffer.alloc(20));
//# sourceMappingURL=currency.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"currency.js","sourceRoot":"","sources":["../../src/types/currency.ts"],"names":[],"mappings":";;;AAAA,yCAAoC;AACpC,oCAAgC;AAEhC,MAAM,aAAa,GAAG,SAAS,CAAA;AAC/B,MAAM,SAAS,GAAG,mCAAmC,CAAA;AACrD,MAAM,SAAS,GAAG,gBAAgB,CAAA;AAClC,4CAA4C;AAC5C,MAAM,yBAAyB,GAAG,4BAA4B,CAAA;AAE9D;;GAEG;AACH,SAAS,UAAU,CAAC,GAAW;IAC7B,MAAM,KAAK,GAAG,eAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;IAC9B,IAAI,GAAG,KAAK,KAAK,EAAE;QACjB,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,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O,GAAG,CAAA;SACX;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,CAAA;IACjD,CAAC;;AAGM,4BAAQ;AAxDC,YAAG,GAAG,IAAI,QAAQ,CAAC,eAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA"}
+17
View File
@@ -0,0 +1,17 @@
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**
* Hash with a width of 128 bits
*/
declare class Hash128 extends Hash {
static readonly width = 16;
static readonly ZERO_128: Hash128;
constructor(bytes: Buffer);
/**
* Get the hex representation of a hash-128 bytes, allowing unset
*
* @returns hex String of this.bytes
*/
toHex(): string;
}
export { Hash128 };
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hash128 = void 0;
const hash_1 = require("./hash");
const buffer_1 = require("buffer/");
/**
* Hash with a width of 128 bits
*/
class Hash128 extends hash_1.Hash {
constructor(bytes) {
if (bytes && bytes.byteLength === 0) {
bytes = Hash128.ZERO_128.bytes;
}
super(bytes !== null && bytes !== void 0 ? bytes : Hash128.ZERO_128.bytes);
}
/**
* Get the hex representation of a hash-128 bytes, allowing unset
*
* @returns hex String of this.bytes
*/
toHex() {
const hex = this.toBytes().toString('hex').toUpperCase();
if (/^0+$/.exec(hex)) {
return '';
}
return hex;
}
}
exports.Hash128 = Hash128;
Hash128.width = 16;
Hash128.ZERO_128 = new Hash128(buffer_1.Buffer.alloc(Hash128.width));
//# sourceMappingURL=hash-128.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hash-128.js","sourceRoot":"","sources":["../../src/types/hash-128.ts"],"names":[],"mappings":";;;AAAA,iCAA6B;AAC7B,oCAAgC;AAEhC;;GAEG;AACH,MAAM,OAAQ,SAAQ,WAAI;IAIxB,YAAY,KAAa;QACvB,IAAI,KAAK,IAAI,KAAK,CAAC,UAAU,KAAK,CAAC,EAAE;YACnC,KAAK,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAA;SAC/B;QAED,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACxC,CAAC;IAED;;;;OAIG;IACH,KAAK;QACH,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,CAAA;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;YACpB,OAAO,EAAE,CAAA;SACV;QACD,OAAO,GAAG,CAAA;IACZ,CAAC;;AAGM,0BAAO;AAzBE,aAAK,GAAG,EAAE,CAAA;AACV,gBAAQ,GAAY,IAAI,OAAO,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA"}
+11
View File
@@ -0,0 +1,11 @@
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**
* Hash with a width of 160 bits
*/
declare class Hash160 extends Hash {
static readonly width = 20;
static readonly ZERO_160: Hash160;
constructor(bytes?: Buffer);
}
export { Hash160 };
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hash160 = void 0;
const hash_1 = require("./hash");
const buffer_1 = require("buffer/");
/**
* Hash with a width of 160 bits
*/
class Hash160 extends hash_1.Hash {
constructor(bytes) {
if (bytes && bytes.byteLength === 0) {
bytes = Hash160.ZERO_160.bytes;
}
super(bytes !== null && bytes !== void 0 ? bytes : Hash160.ZERO_160.bytes);
}
}
exports.Hash160 = Hash160;
Hash160.width = 20;
Hash160.ZERO_160 = new Hash160(buffer_1.Buffer.alloc(Hash160.width));
//# sourceMappingURL=hash-160.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hash-160.js","sourceRoot":"","sources":["../../src/types/hash-160.ts"],"names":[],"mappings":";;;AAAA,iCAA6B;AAC7B,oCAAgC;AAEhC;;GAEG;AACH,MAAM,OAAQ,SAAQ,WAAI;IAIxB,YAAY,KAAc;QACxB,IAAI,KAAK,IAAI,KAAK,CAAC,UAAU,KAAK,CAAC,EAAE;YACnC,KAAK,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAA;SAC/B;QAED,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACxC,CAAC;;AAGM,0BAAO;AAZE,aAAK,GAAG,EAAE,CAAA;AACV,gBAAQ,GAAY,IAAI,OAAO,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA"}
+11
View File
@@ -0,0 +1,11 @@
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**
* Hash with a width of 256 bits
*/
declare class Hash256 extends Hash {
static readonly width = 32;
static readonly ZERO_256: Hash256;
constructor(bytes: Buffer);
}
export { Hash256 };
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hash256 = void 0;
const hash_1 = require("./hash");
const buffer_1 = require("buffer/");
/**
* Hash with a width of 256 bits
*/
class Hash256 extends hash_1.Hash {
constructor(bytes) {
super(bytes !== null && bytes !== void 0 ? bytes : Hash256.ZERO_256.bytes);
}
}
exports.Hash256 = Hash256;
Hash256.width = 32;
Hash256.ZERO_256 = new Hash256(buffer_1.Buffer.alloc(Hash256.width));
//# sourceMappingURL=hash-256.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hash-256.js","sourceRoot":"","sources":["../../src/types/hash-256.ts"],"names":[],"mappings":";;;AAAA,iCAA6B;AAC7B,oCAAgC;AAEhC;;GAEG;AACH,MAAM,OAAQ,SAAQ,WAAI;IAIxB,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACxC,CAAC;;AAGM,0BAAO;AARE,aAAK,GAAG,EAAE,CAAA;AACV,gBAAQ,GAAG,IAAI,OAAO,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA"}
+41
View File
@@ -0,0 +1,41 @@
import { Comparable } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**
* Base class defining how to encode and decode hashes
*/
declare class Hash extends Comparable {
static readonly width: number;
constructor(bytes: Buffer);
/**
* Construct a Hash object from an existing Hash object or a hex-string
*
* @param value A hash object or hex-string of a hash
*/
static from<T extends Hash | string>(value: T): Hash;
/**
* Read a Hash object from a BinaryParser
*
* @param parser BinaryParser to read the hash from
* @param hint length of the bytes to read, optional
*/
static fromParser(parser: BinaryParser, hint?: number): Hash;
/**
* Overloaded operator for comparing two hash objects
*
* @param other The Hash to compare this to
*/
compareTo(other: Hash): number;
/**
* @returns the hex-string representation of this Hash
*/
toString(): string;
/**
* Returns four bits at the specified depth within a hash
*
* @param depth The depth of the four bits
* @returns The number represented by the four bits
*/
nibblet(depth: number): number;
}
export { Hash };
+72
View File
@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hash = void 0;
const serialized_type_1 = require("./serialized-type");
const buffer_1 = require("buffer/");
/**
* Base class defining how to encode and decode hashes
*/
class Hash extends serialized_type_1.Comparable {
constructor(bytes) {
super(bytes);
if (this.bytes.byteLength !== this.constructor.width) {
throw new Error(`Invalid Hash length ${this.bytes.byteLength}`);
}
}
/**
* Construct a Hash object from an existing Hash object or a hex-string
*
* @param value A hash object or hex-string of a hash
*/
static from(value) {
if (value instanceof this) {
return value;
}
if (typeof value === 'string') {
return new this(buffer_1.Buffer.from(value, 'hex'));
}
throw new Error('Cannot construct Hash from given value');
}
/**
* Read a Hash object from a BinaryParser
*
* @param parser BinaryParser to read the hash from
* @param hint length of the bytes to read, optional
*/
static fromParser(parser, hint) {
return new this(parser.read(hint !== null && hint !== void 0 ? hint : this.width));
}
/**
* Overloaded operator for comparing two hash objects
*
* @param other The Hash to compare this to
*/
compareTo(other) {
return this.bytes.compare(this.constructor.from(other).bytes);
}
/**
* @returns the hex-string representation of this Hash
*/
toString() {
return this.toHex();
}
/**
* Returns four bits at the specified depth within a hash
*
* @param depth The depth of the four bits
* @returns The number represented by the four bits
*/
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;
}
}
exports.Hash = Hash;
//# sourceMappingURL=hash.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/types/hash.ts"],"names":[],"mappings":";;;AAAA,uDAA8C;AAE9C,oCAAgC;AAEhC;;GAEG;AACH,MAAM,IAAK,SAAQ,4BAAU;IAG3B,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,CAAC,CAAA;QACZ,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,KAAM,IAAI,CAAC,WAA2B,CAAC,KAAK,EAAE;YACrE,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAA;SAChE;IACH,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAA0B,KAAQ;QAC3C,IAAI,KAAK,YAAY,IAAI,EAAE;YACzB,OAAO,KAAK,CAAA;SACb;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,OAAO,IAAI,IAAI,CAAC,eAAM,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;SAC3C;QAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IAC3D,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,UAAU,CAAC,MAAoB,EAAE,IAAa;QACnD,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAClD,CAAC;IAED;;;;OAIG;IACH,SAAS,CAAC,KAAW;QACnB,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CACtB,IAAI,CAAC,WAA2B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CACpD,CAAA;IACH,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,KAAa;QACnB,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9C,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;QAC1B,IAAI,KAAK,GAAG,CAAC,KAAK,CAAC,EAAE;YACnB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAA;SACrB;aAAM;YACL,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;SACb;QACD,OAAO,CAAC,CAAA;IACV,CAAC;CACF;AAEQ,oBAAI"}
+33
View File
@@ -0,0 +1,33 @@
import { AccountID } from './account-id';
import { Amount } from './amount';
import { Blob } from './blob';
import { Currency } from './currency';
import { Hash128 } from './hash-128';
import { Hash160 } from './hash-160';
import { Hash256 } from './hash-256';
import { PathSet } from './path-set';
import { STArray } from './st-array';
import { STObject } from './st-object';
import { UInt16 } from './uint-16';
import { UInt32 } from './uint-32';
import { UInt64 } from './uint-64';
import { UInt8 } from './uint-8';
import { Vector256 } from './vector-256';
declare const coreTypes: {
AccountID: typeof AccountID;
Amount: typeof Amount;
Blob: typeof Blob;
Currency: typeof Currency;
Hash128: typeof Hash128;
Hash160: typeof Hash160;
Hash256: typeof Hash256;
PathSet: typeof PathSet;
STArray: typeof STArray;
STObject: typeof STObject;
UInt8: typeof UInt8;
UInt16: typeof UInt16;
UInt32: typeof UInt32;
UInt64: typeof UInt64;
Vector256: typeof Vector256;
};
export { coreTypes };
+44
View File
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.coreTypes = void 0;
const enums_1 = require("../enums");
const account_id_1 = require("./account-id");
const amount_1 = require("./amount");
const blob_1 = require("./blob");
const currency_1 = require("./currency");
const hash_128_1 = require("./hash-128");
const hash_160_1 = require("./hash-160");
const hash_256_1 = require("./hash-256");
const path_set_1 = require("./path-set");
const st_array_1 = require("./st-array");
const st_object_1 = require("./st-object");
const uint_16_1 = require("./uint-16");
const uint_32_1 = require("./uint-32");
const uint_64_1 = require("./uint-64");
const uint_8_1 = require("./uint-8");
const vector_256_1 = require("./vector-256");
const coreTypes = {
AccountID: account_id_1.AccountID,
Amount: amount_1.Amount,
Blob: blob_1.Blob,
Currency: currency_1.Currency,
Hash128: hash_128_1.Hash128,
Hash160: hash_160_1.Hash160,
Hash256: hash_256_1.Hash256,
PathSet: path_set_1.PathSet,
STArray: st_array_1.STArray,
STObject: st_object_1.STObject,
UInt8: uint_8_1.UInt8,
UInt16: uint_16_1.UInt16,
UInt32: uint_32_1.UInt32,
UInt64: uint_64_1.UInt64,
Vector256: vector_256_1.Vector256,
};
exports.coreTypes = coreTypes;
Object.values(enums_1.Field).forEach((field) => {
field.associatedType = coreTypes[field.type.name];
});
enums_1.Field['TransactionType'].associatedType = enums_1.TransactionType;
enums_1.Field['TransactionResult'].associatedType = enums_1.TransactionResult;
enums_1.Field['LedgerEntryType'].associatedType = enums_1.LedgerEntryType;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":";;;AAAA,oCAKiB;AACjB,6CAAwC;AACxC,qCAAiC;AACjC,iCAA6B;AAC7B,yCAAqC;AACrC,yCAAoC;AACpC,yCAAoC;AACpC,yCAAoC;AACpC,yCAAoC;AACpC,yCAAoC;AACpC,2CAAsC;AACtC,uCAAkC;AAClC,uCAAkC;AAClC,uCAAkC;AAClC,qCAAgC;AAChC,6CAAwC;AAExC,MAAM,SAAS,GAAG;IAChB,SAAS,EAAT,sBAAS;IACT,MAAM,EAAN,eAAM;IACN,IAAI,EAAJ,WAAI;IACJ,QAAQ,EAAR,mBAAQ;IACR,OAAO,EAAP,kBAAO;IACP,OAAO,EAAP,kBAAO;IACP,OAAO,EAAP,kBAAO;IACP,OAAO,EAAP,kBAAO;IACP,OAAO,EAAP,kBAAO;IACP,QAAQ,EAAR,oBAAQ;IACR,KAAK,EAAL,cAAK;IACL,MAAM,EAAN,gBAAM;IACN,MAAM,EAAN,gBAAM;IACN,MAAM,EAAN,gBAAM;IACN,SAAS,EAAT,sBAAS;CACV,CAAA;AAUQ,8BAAS;AARlB,MAAM,CAAC,MAAM,CAAC,aAAK,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;IACrC,KAAK,CAAC,cAAc,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACnD,CAAC,CAAC,CAAA;AAEF,aAAK,CAAC,iBAAiB,CAAC,CAAC,cAAc,GAAG,uBAAe,CAAA;AACzD,aAAK,CAAC,mBAAmB,CAAC,CAAC,cAAc,GAAG,yBAAiB,CAAA;AAC7D,aAAK,CAAC,iBAAiB,CAAC,CAAC,cAAc,GAAG,uBAAe,CAAA"}
+36
View File
@@ -0,0 +1,36 @@
import { BinaryParser } from '../serdes/binary-parser';
import { SerializedType, JsonObject } from './serialized-type';
/**
* The object representation of a Hop, an issuer AccountID, an account AccountID, and a Currency
*/
interface HopObject extends JsonObject {
issuer?: string;
account?: string;
currency?: string;
}
/**
* Deserialize and Serialize the PathSet type
*/
declare class PathSet extends SerializedType {
/**
* Construct a PathSet from an Array of Arrays representing paths
*
* @param value A PathSet or Array of Array of HopObjects
* @returns the PathSet constructed from value
*/
static from<T extends PathSet | Array<Array<HopObject>>>(value: T): PathSet;
/**
* Construct a PathSet from a BinaryParser
*
* @param parser A BinaryParser to read PathSet from
* @returns the PathSet read from parser
*/
static fromParser(parser: BinaryParser): PathSet;
/**
* Get the JSON representation of this PathSet
*
* @returns an Array of Array of HopObjects, representing this PathSet
*/
toJSON(): Array<Array<HopObject>>;
}
export { PathSet };
+233
View File
@@ -0,0 +1,233 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathSet = void 0;
const account_id_1 = require("./account-id");
const currency_1 = require("./currency");
const binary_parser_1 = require("../serdes/binary-parser");
const serialized_type_1 = require("./serialized-type");
const buffer_1 = require("buffer/");
/**
* Constants for separating Paths in a PathSet
*/
const PATHSET_END_BYTE = 0x00;
const PATH_SEPARATOR_BYTE = 0xff;
/**
* Constant for masking types of a Hop
*/
const TYPE_ACCOUNT = 0x01;
const TYPE_CURRENCY = 0x10;
const TYPE_ISSUER = 0x20;
/**
* TypeGuard for HopObject
*/
function isHopObject(arg) {
return (arg.issuer !== undefined ||
arg.account !== undefined ||
arg.currency !== undefined);
}
/**
* TypeGuard for PathSet
*/
function isPathSet(arg) {
return ((Array.isArray(arg) && arg.length === 0) ||
(Array.isArray(arg) && Array.isArray(arg[0]) && arg[0].length === 0) ||
(Array.isArray(arg) && Array.isArray(arg[0]) && isHopObject(arg[0][0])));
}
/**
* Serialize and Deserialize a Hop
*/
class Hop extends serialized_type_1.SerializedType {
/**
* Create a Hop from a HopObject
*
* @param value Either a hop or HopObject to create a hop with
* @returns a Hop
*/
static from(value) {
if (value instanceof Hop) {
return value;
}
const bytes = [buffer_1.Buffer.from([0])];
if (value.account) {
bytes.push(account_id_1.AccountID.from(value.account).toBytes());
bytes[0][0] |= TYPE_ACCOUNT;
}
if (value.currency) {
bytes.push(currency_1.Currency.from(value.currency).toBytes());
bytes[0][0] |= TYPE_CURRENCY;
}
if (value.issuer) {
bytes.push(account_id_1.AccountID.from(value.issuer).toBytes());
bytes[0][0] |= TYPE_ISSUER;
}
return new Hop(buffer_1.Buffer.concat(bytes));
}
/**
* Construct a Hop from a BinaryParser
*
* @param parser BinaryParser to read the Hop from
* @returns a Hop
*/
static fromParser(parser) {
const type = parser.readUInt8();
const bytes = [buffer_1.Buffer.from([type])];
if (type & TYPE_ACCOUNT) {
bytes.push(parser.read(account_id_1.AccountID.width));
}
if (type & TYPE_CURRENCY) {
bytes.push(parser.read(currency_1.Currency.width));
}
if (type & TYPE_ISSUER) {
bytes.push(parser.read(account_id_1.AccountID.width));
}
return new Hop(buffer_1.Buffer.concat(bytes));
}
/**
* Get the JSON interpretation of this hop
*
* @returns a HopObject, an JS object with optional account, issuer, and currency
*/
toJSON() {
const hopParser = new binary_parser_1.BinaryParser(this.bytes.toString('hex'));
const type = hopParser.readUInt8();
let account, currency, issuer;
if (type & TYPE_ACCOUNT) {
account = account_id_1.AccountID.fromParser(hopParser).toJSON();
}
if (type & TYPE_CURRENCY) {
currency = currency_1.Currency.fromParser(hopParser).toJSON();
}
if (type & TYPE_ISSUER) {
issuer = account_id_1.AccountID.fromParser(hopParser).toJSON();
}
const result = {};
if (account) {
result.account = account;
}
if (issuer) {
result.issuer = issuer;
}
if (currency) {
result.currency = currency;
}
return result;
}
/**
* get a number representing the type of this hop
*
* @returns a number to be bitwise and-ed with TYPE_ constants to describe the types in the hop
*/
type() {
return this.bytes[0];
}
}
/**
* Class for serializing/deserializing Paths
*/
class Path extends serialized_type_1.SerializedType {
/**
* construct a Path from an array of Hops
*
* @param value Path or array of HopObjects to construct a Path
* @returns the Path
*/
static from(value) {
if (value instanceof Path) {
return value;
}
const bytes = [];
value.forEach((hop) => {
bytes.push(Hop.from(hop).toBytes());
});
return new Path(buffer_1.Buffer.concat(bytes));
}
/**
* Read a Path from a BinaryParser
*
* @param parser BinaryParser to read Path from
* @returns the Path represented by the bytes read from the BinaryParser
*/
static fromParser(parser) {
const bytes = [];
while (!parser.end()) {
bytes.push(Hop.fromParser(parser).toBytes());
if (parser.peek() === PATHSET_END_BYTE ||
parser.peek() === PATH_SEPARATOR_BYTE) {
break;
}
}
return new Path(buffer_1.Buffer.concat(bytes));
}
/**
* Get the JSON representation of this Path
*
* @returns an Array of HopObject constructed from this.bytes
*/
toJSON() {
const json = [];
const pathParser = new binary_parser_1.BinaryParser(this.toString());
while (!pathParser.end()) {
json.push(Hop.fromParser(pathParser).toJSON());
}
return json;
}
}
/**
* Deserialize and Serialize the PathSet type
*/
class PathSet extends serialized_type_1.SerializedType {
/**
* Construct a PathSet from an Array of Arrays representing paths
*
* @param value A PathSet or Array of Array of HopObjects
* @returns the PathSet constructed from value
*/
static from(value) {
if (value instanceof PathSet) {
return value;
}
if (isPathSet(value)) {
const bytes = [];
value.forEach((path) => {
bytes.push(Path.from(path).toBytes());
bytes.push(buffer_1.Buffer.from([PATH_SEPARATOR_BYTE]));
});
bytes[bytes.length - 1] = buffer_1.Buffer.from([PATHSET_END_BYTE]);
return new PathSet(buffer_1.Buffer.concat(bytes));
}
throw new Error('Cannot construct PathSet from given value');
}
/**
* Construct a PathSet from a BinaryParser
*
* @param parser A BinaryParser to read PathSet from
* @returns the PathSet read from parser
*/
static fromParser(parser) {
const bytes = [];
while (!parser.end()) {
bytes.push(Path.fromParser(parser).toBytes());
bytes.push(parser.read(1));
if (bytes[bytes.length - 1][0] == PATHSET_END_BYTE) {
break;
}
}
return new PathSet(buffer_1.Buffer.concat(bytes));
}
/**
* Get the JSON representation of this PathSet
*
* @returns an Array of Array of HopObjects, representing this PathSet
*/
toJSON() {
const json = [];
const pathParser = new binary_parser_1.BinaryParser(this.toString());
while (!pathParser.end()) {
json.push(Path.fromParser(pathParser).toJSON());
pathParser.skip(1);
}
return json;
}
}
exports.PathSet = PathSet;
//# sourceMappingURL=path-set.js.map
File diff suppressed because one or more lines are too long
+63
View File
@@ -0,0 +1,63 @@
import { BytesList } from '../serdes/binary-serializer';
import { BinaryParser } from '../serdes/binary-parser';
import bigInt = require('big-integer');
import { Buffer } from 'buffer/';
type JSON = string | number | boolean | null | undefined | JSON[] | JsonObject;
type JsonObject = {
[key: string]: JSON;
};
/**
* The base class for all binary-codec types
*/
declare class SerializedType {
protected readonly bytes: Buffer;
constructor(bytes: Buffer);
static fromParser(parser: BinaryParser, hint?: number): SerializedType;
static from(value: SerializedType | JSON | bigInt.BigInteger): SerializedType;
/**
* Write the bytes representation of a SerializedType to a BytesList
*
* @param list The BytesList to write SerializedType bytes to
*/
toBytesSink(list: BytesList): void;
/**
* Get the hex representation of a SerializedType's bytes
*
* @returns hex String of this.bytes
*/
toHex(): string;
/**
* Get the bytes representation of a SerializedType
*
* @returns A buffer of the bytes
*/
toBytes(): Buffer;
/**
* Return the JSON representation of a SerializedType
*
* @returns any type, if not overloaded returns hexString representation of bytes
*/
toJSON(): JSON;
/**
* @returns hexString representation of this.bytes
*/
toString(): string;
}
/**
* Base class for SerializedTypes that are comparable
*/
declare class Comparable extends SerializedType {
lt(other: Comparable): boolean;
eq(other: Comparable): boolean;
gt(other: Comparable): boolean;
gte(other: Comparable): boolean;
lte(other: Comparable): boolean;
/**
* Overload this method to define how two Comparable SerializedTypes are compared
*
* @param other The comparable object to compare this to
* @returns A number denoting the relationship of this and other
*/
compareTo(other: Comparable): number;
}
export { SerializedType, Comparable, JSON, JsonObject };
+97
View File
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Comparable = exports.SerializedType = void 0;
const binary_serializer_1 = require("../serdes/binary-serializer");
const buffer_1 = require("buffer/");
/**
* The base class for all binary-codec types
*/
class SerializedType {
constructor(bytes) {
this.bytes = buffer_1.Buffer.alloc(0);
this.bytes = bytes !== null && bytes !== void 0 ? bytes : buffer_1.Buffer.alloc(0);
}
static fromParser(parser, hint) {
throw new Error('fromParser not implemented');
return this.fromParser(parser, hint);
}
static from(value) {
throw new Error('from not implemented');
return this.from(value);
}
/**
* Write the bytes representation of a SerializedType to a BytesList
*
* @param list The BytesList to write SerializedType bytes to
*/
toBytesSink(list) {
list.put(this.bytes);
}
/**
* Get the hex representation of a SerializedType's bytes
*
* @returns hex String of this.bytes
*/
toHex() {
return this.toBytes().toString('hex').toUpperCase();
}
/**
* Get the bytes representation of a SerializedType
*
* @returns A buffer of the bytes
*/
toBytes() {
if (this.bytes) {
return this.bytes;
}
const bytes = new binary_serializer_1.BytesList();
this.toBytesSink(bytes);
return bytes.toBytes();
}
/**
* Return the JSON representation of a SerializedType
*
* @returns any type, if not overloaded returns hexString representation of bytes
*/
toJSON() {
return this.toHex();
}
/**
* @returns hexString representation of this.bytes
*/
toString() {
return this.toHex();
}
}
exports.SerializedType = SerializedType;
/**
* Base class for SerializedTypes that are comparable
*/
class Comparable extends SerializedType {
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;
}
/**
* Overload this method to define how two Comparable SerializedTypes are compared
*
* @param other The comparable object to compare this to
* @returns A number denoting the relationship of this and other
*/
compareTo(other) {
throw new Error(`cannot compare ${this.toString()} and ${other.toString()}`);
}
}
exports.Comparable = Comparable;
//# sourceMappingURL=serialized-type.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"serialized-type.js","sourceRoot":"","sources":["../../src/types/serialized-type.ts"],"names":[],"mappings":";;;AAAA,mEAAuD;AAGvD,oCAAgC;AAMhC;;GAEG;AACH,MAAM,cAAc;IAGlB,YAAY,KAAa;QAFN,UAAK,GAAW,eAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAGhD,IAAI,CAAC,KAAK,GAAG,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,eAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAoB,EAAE,IAAa;QACnD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;QAC7C,O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IAClC,CAAC;IAED,GAAG,CAAC,KAAiB;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAA;IACnC,CAAC;IAED,GAAG,CAAC,KAAiB;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAClC,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAAC,KAAiB;QACzB,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,CAAC,QAAQ,EAAE,QAAQ,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;IAC9E,CAAC;CACF;AAEwB,gCAAU"}
+28
View File
@@ -0,0 +1,28 @@
import { SerializedType, JsonObject } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
/**
* Class for serializing and deserializing Arrays of Objects
*/
declare class STArray extends SerializedType {
/**
* Construct an STArray from a BinaryParser
*
* @param parser BinaryParser to parse an STArray from
* @returns An STArray Object
*/
static fromParser(parser: BinaryParser): STArray;
/**
* Construct an STArray from an Array of JSON Objects
*
* @param value STArray or Array of Objects to parse into an STArray
* @returns An STArray object
*/
static from<T extends STArray | Array<JsonObject>>(value: T): STArray;
/**
* Return the JSON representation of this.bytes
*
* @returns An Array of JSON objects
*/
toJSON(): Array<JsonObject>;
}
export { STArray };
+80
View File
@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STArray = void 0;
const serialized_type_1 = require("./serialized-type");
const st_object_1 = require("./st-object");
const binary_parser_1 = require("../serdes/binary-parser");
const buffer_1 = require("buffer/");
const ARRAY_END_MARKER = buffer_1.Buffer.from([0xf1]);
const ARRAY_END_MARKER_NAME = 'ArrayEndMarker';
const OBJECT_END_MARKER = buffer_1.Buffer.from([0xe1]);
/**
* TypeGuard for Array<JsonObject>
*/
function isObjects(args) {
return (Array.isArray(args) && (args.length === 0 || typeof args[0] === 'object'));
}
/**
* Class for serializing and deserializing Arrays of Objects
*/
class STArray extends serialized_type_1.SerializedType {
/**
* Construct an STArray from a BinaryParser
*
* @param parser BinaryParser to parse an STArray from
* @returns An STArray Object
*/
static fromParser(parser) {
const bytes = [];
while (!parser.end()) {
const field = parser.readField();
if (field.name === ARRAY_END_MARKER_NAME) {
break;
}
bytes.push(field.header, parser.readFieldValue(field).toBytes(), OBJECT_END_MARKER);
}
bytes.push(ARRAY_END_MARKER);
return new STArray(buffer_1.Buffer.concat(bytes));
}
/**
* Construct an STArray from an Array of JSON Objects
*
* @param value STArray or Array of Objects to parse into an STArray
* @returns An STArray object
*/
static from(value) {
if (value instanceof STArray) {
return value;
}
if (isObjects(value)) {
const bytes = [];
value.forEach((obj) => {
bytes.push(st_object_1.STObject.from(obj).toBytes());
});
bytes.push(ARRAY_END_MARKER);
return new STArray(buffer_1.Buffer.concat(bytes));
}
throw new Error('Cannot construct STArray from value given');
}
/**
* Return the JSON representation of this.bytes
*
* @returns An Array of JSON objects
*/
toJSON() {
const result = [];
const arrayParser = new binary_parser_1.BinaryParser(this.toString());
while (!arrayParser.end()) {
const field = arrayParser.readField();
if (field.name === ARRAY_END_MARKER_NAME) {
break;
}
const outer = {};
outer[field.name] = st_object_1.STObject.fromParser(arrayParser).toJSON();
result.push(outer);
}
return result;
}
}
exports.STArray = STArray;
//# sourceMappingURL=st-array.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"st-array.js","sourceRoot":"","sources":["../../src/types/st-array.ts"],"names":[],"mappings":";;;AAAA,uDAA8D;AAC9D,2CAAsC;AACtC,2DAAsD;AACtD,oCAAgC;AAEhC,MAAM,gBAAgB,GAAG,eAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AAC5C,MAAM,qBAAqB,GAAG,gBAAgB,CAAA;AAE9C,MAAM,iBAAiB,GAAG,eAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AAE7C;;GAEG;AACH,SAAS,SAAS,CAAC,IAAI;IACrB,OAAO,CAC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AK,CAAC,CAAC,CAAA;SACzC;QAED,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAA;IAC9D,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,MAAM,MAAM,GAAsB,EAAE,CAAA;QAEpC,MAAM,WAAW,GAAG,IAAI,4BAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAA;QAErD,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,EAAE;YACzB,MAAM,KAAK,GAAG,WAAW,CAAC,SAAS,EAAE,CAAA;YACrC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB,EAAE;gBACxC,MAAK;aACN;YAED,MAAM,KAAK,GAAG,EAAE,CAAA;YAChB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,oBAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,MAAM,EAAE,CAAA;YAC7D,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;SACnB;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAEQ,0BAAO"}
+29
View File
@@ -0,0 +1,29 @@
import { SerializedType, JsonObject } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
/**
* Class for Serializing/Deserializing objects
*/
declare class STObject extends SerializedType {
/**
* Construct a STObject from a BinaryParser
*
* @param parser BinaryParser to read STObject from
* @returns A STObject object
*/
static fromParser(parser: BinaryParser): STObject;
/**
* Construct a STObject from a JSON object
*
* @param value An object to include
* @param filter optional, denote which field to include in serialized object
* @returns a STObject object
*/
static from<T extends STObject | JsonObject>(value: T, filter?: (...any: any[]) => boolean): STObject;
/**
* Get the JSON interpretation of this.bytes
*
* @returns a JSON object
*/
toJSON(): JsonObject;
}
export { STObject };
+147
View File
@@ -0,0 +1,147 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STObject = void 0;
const enums_1 = require("../enums");
const serialized_type_1 = require("./serialized-type");
const ripple_address_codec_1 = require("ripple-address-codec");
const binary_parser_1 = require("../serdes/binary-parser");
const binary_serializer_1 = require("../serdes/binary-serializer");
const buffer_1 = require("buffer/");
const OBJECT_END_MARKER_BYTE = buffer_1.Buffer.from([0xe1]);
const OBJECT_END_MARKER = 'ObjectEndMarker';
const ST_OBJECT = 'STObject';
const DESTINATION = 'Destination';
const ACCOUNT = 'Account';
const SOURCE_TAG = 'SourceTag';
const DEST_TAG = 'DestinationTag';
/**
* Break down an X-Address into an account and a tag
*
* @param field Name of field
* @param xAddress X-Address corresponding to the field
*/
function handleXAddress(field, xAddress) {
const decoded = (0, ripple_address_codec_1.xAddressToClassicAddress)(xAddress);
let tagName;
if (field === DESTINATION)
tagName = DEST_TAG;
else if (field === ACCOUNT)
tagName = SOURCE_TAG;
else if (decoded.tag !== false)
throw new Error(`${field} cannot have an associated tag`);
return decoded.tag !== false
? { [field]: decoded.classicAddress, [tagName]: decoded.tag }
: { [field]: decoded.classicAddress };
}
/**
* Validate that two objects don't both have the same tag fields
*
* @param obj1 First object to check for tags
* @param obj2 Second object to check for tags
* @throws When both objects have SourceTag or DestinationTag
*/
function checkForDuplicateTags(obj1, obj2) {
if (!(obj1[SOURCE_TAG] === undefined || obj2[SOURCE_TAG] === undefined))
throw new Error('Cannot have Account X-Address and SourceTag');
if (!(obj1[DEST_TAG] === undefined || obj2[DEST_TAG] === undefined))
throw new Error('Cannot have Destination X-Address and DestinationTag');
}
/**
* Class for Serializing/Deserializing objects
*/
class STObject extends serialized_type_1.SerializedType {
/**
* Construct a STObject from a BinaryParser
*
* @param parser BinaryParser to read STObject from
* @returns A STObject object
*/
static fromParser(parser) {
const list = new binary_serializer_1.BytesList();
const bytes = new binary_serializer_1.BinarySerializer(list);
while (!parser.end()) {
const field = parser.readField();
if (field.name === OBJECT_END_MARKER) {
break;
}
const associatedValue = parser.readFieldValue(field);
bytes.writeFieldAndValue(field, associatedValue);
if (field.type.name === ST_OBJECT) {
bytes.put(OBJECT_END_MARKER_BYTE);
}
}
return new STObject(list.toBytes());
}
/**
* Construct a STObject from a JSON object
*
* @param value An object to include
* @param filter optional, denote which field to include in serialized object
* @returns a STObject object
*/
static from(value, filter) {
if (value instanceof STObject) {
return value;
}
const list = new binary_serializer_1.BytesList();
const bytes = new binary_serializer_1.BinarySerializer(list);
let isUnlModify = false;
const xAddressDecoded = Object.entries(value).reduce((acc, [key, val]) => {
let handled = undefined;
if (val && (0, ripple_address_codec_1.isValidXAddress)(val.toString())) {
handled = handleXAddress(key, val.toString());
checkForDuplicateTags(handled, value);
}
return Object.assign(acc, handled !== null && handled !== void 0 ? handled : { [key]: val });
}, {});
let sorted = Object.keys(xAddressDecoded)
.map((f) => enums_1.Field[f])
.filter((f) => f !== undefined &&
xAddressDecoded[f.name] !== undefined &&
f.isSerialized)
.sort((a, b) => {
return a.ordinal - b.ordinal;
});
if (filter !== undefined) {
sorted = sorted.filter(filter);
}
sorted.forEach((field) => {
const associatedValue = field.associatedType.from(xAddressDecoded[field.name]);
if (associatedValue == undefined) {
throw new TypeError(`Unable to interpret "${field.name}: ${xAddressDecoded[field.name]}".`);
}
if (associatedValue.name === 'UNLModify') {
// triggered when the TransactionType field has a value of 'UNLModify'
isUnlModify = true;
}
// true when in the UNLModify pseudotransaction (after the transaction type has been processed) and working with the
// Account field
// The Account field must not be a part of the UNLModify pseudotransaction encoding, due to a bug in rippled
const isUnlModifyWorkaround = field.name == 'Account' && isUnlModify;
bytes.writeFieldAndValue(field, associatedValue, isUnlModifyWorkaround);
if (field.type.name === ST_OBJECT) {
bytes.put(OBJECT_END_MARKER_BYTE);
}
});
return new STObject(list.toBytes());
}
/**
* Get the JSON interpretation of this.bytes
*
* @returns a JSON object
*/
toJSON() {
const objectParser = new binary_parser_1.BinaryParser(this.toString());
const accumulator = {};
while (!objectParser.end()) {
const field = objectParser.readField();
if (field.name === OBJECT_END_MARKER) {
break;
}
accumulator[field.name] = objectParser.readFieldValue(field).toJSON();
}
return accumulator;
}
}
exports.STObject = STObject;
//# sourceMappingURL=st-object.js.map
+1
View File
@@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"}
+25
View File
@@ -0,0 +1,25 @@
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**
* Derived UInt class for serializing/deserializing 16 bit UInt
*/
declare class UInt16 extends UInt {
protected static readonly width: number;
static readonly defaultUInt16: UInt16;
constructor(bytes: Buffer);
static fromParser(parser: BinaryParser): UInt;
/**
* Construct a UInt16 object from a number
*
* @param val UInt16 object or number
*/
static from<T extends UInt16 | number>(val: T): UInt16;
/**
* get the value of a UInt16 object
*
* @returns the number represented by this.bytes
*/
valueOf(): number;
}
export { UInt16 };
+44
View File
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UInt16 = void 0;
const uint_1 = require("./uint");
const buffer_1 = require("buffer/");
/**
* Derived UInt class for serializing/deserializing 16 bit UInt
*/
class UInt16 extends uint_1.UInt {
constructor(bytes) {
super(bytes !== null && bytes !== void 0 ? bytes : UInt16.defaultUInt16.bytes);
}
static fromParser(parser) {
return new UInt16(parser.read(UInt16.width));
}
/**
* Construct a UInt16 object from a number
*
* @param val UInt16 object or number
*/
static from(val) {
if (val instanceof UInt16) {
return val;
}
if (typeof val === 'number') {
const buf = buffer_1.Buffer.alloc(UInt16.width);
buf.writeUInt16BE(val, 0);
return new UInt16(buf);
}
throw new Error('Can not construct UInt16 with given value');
}
/**
* get the value of a UInt16 object
*
* @returns the number represented by this.bytes
*/
valueOf() {
return this.bytes.readUInt16BE(0);
}
}
exports.UInt16 = UInt16;
UInt16.width = 16 / 8; // 2
UInt16.defaultUInt16 = new UInt16(buffer_1.Buffer.alloc(UInt16.width));
//# sourceMappingURL=uint-16.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uint-16.js","sourceRoot":"","sources":["../../src/types/uint-16.ts"],"names":[],"mappings":";;;AAAA,iCAA6B;AAE7B,oCAAgC;AAEhC;;GAEG;AACH,MAAM,MAAO,SAAQ,WAAI;IAIvB,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;IAC5C,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAoB;QACpC,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;IAC9C,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAA4B,GAAM;QAC3C,IAAI,GAAG,YAAY,MAAM,EAAE;YACzB,OAAO,GAAG,CAAA;SACX;QAED,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,GAAG,GAAG,eAAM,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACtC,GAAG,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;YACzB,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,CAAA;SACvB;QAED,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAA;IAC9D,CAAC;IAED;;;;OAIG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;IACnC,CAAC;;AAGM,wBAAM;AAxCa,YAAK,GAAW,EAAE,GAAG,CAAC,CAAA,CAAC,IAAI;AACrC,oBAAa,GAAW,IAAI,MAAM,CAAC,eAAM,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA"}
+25
View File
@@ -0,0 +1,25 @@
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**
* Derived UInt class for serializing/deserializing 32 bit UInt
*/
declare class UInt32 extends UInt {
protected static readonly width: number;
static readonly defaultUInt32: UInt32;
constructor(bytes: Buffer);
static fromParser(parser: BinaryParser): UInt;
/**
* Construct a UInt32 object from a number
*
* @param val UInt32 object or number
*/
static from<T extends UInt32 | number | string>(val: T): UInt32;
/**
* get the value of a UInt32 object
*
* @returns the number represented by this.bytes
*/
valueOf(): number;
}
export { UInt32 };
+49
View File
@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UInt32 = void 0;
const uint_1 = require("./uint");
const buffer_1 = require("buffer/");
/**
* Derived UInt class for serializing/deserializing 32 bit UInt
*/
class UInt32 extends uint_1.UInt {
constructor(bytes) {
super(bytes !== null && bytes !== void 0 ? bytes : UInt32.defaultUInt32.bytes);
}
static fromParser(parser) {
return new UInt32(parser.read(UInt32.width));
}
/**
* Construct a UInt32 object from a number
*
* @param val UInt32 object or number
*/
static from(val) {
if (val instanceof UInt32) {
return val;
}
const buf = buffer_1.Buffer.alloc(UInt32.width);
if (typeof val === 'string') {
const num = Number.parseInt(val);
buf.writeUInt32BE(num, 0);
return new UInt32(buf);
}
if (typeof val === 'number') {
buf.writeUInt32BE(val, 0);
return new UInt32(buf);
}
throw new Error('Cannot construct UInt32 from given value');
}
/**
* get the value of a UInt32 object
*
* @returns the number represented by this.bytes
*/
valueOf() {
return this.bytes.readUInt32BE(0);
}
}
exports.UInt32 = UInt32;
UInt32.width = 32 / 8; // 4
UInt32.defaultUInt32 = new UInt32(buffer_1.Buffer.alloc(UInt32.width));
//# sourceMappingURL=uint-32.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uint-32.js","sourceRoot":"","sources":["../../src/types/uint-32.ts"],"names":[],"mappings":";;;AAAA,iCAA6B;AAE7B,oCAAgC;AAEhC;;GAEG;AACH,MAAM,MAAO,SAAQ,WAAI;IAIvB,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;IAC5C,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAoB;QACpC,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;IAC9C,CAAC;IAED;;;;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